const io = require('socket.io-client'); console.log('🔍 测试不同WebSocket协议的差异'); console.log('='.repeat(50)); async function testProtocol(name, url, options) { console.log(`\n🧪 测试: ${name}`); console.log(`📡 URL: ${url}`); return new Promise((resolve) => { const socket = io(url, options); let resolved = false; const timeout = setTimeout(() => { if (!resolved) { resolved = true; socket.disconnect(); console.log(' ❌ 连接超时'); resolve({ success: false, error: 'timeout' }); } }, 8000); socket.on('connect', () => { if (!resolved) { resolved = true; clearTimeout(timeout); console.log(' ✅ 连接成功'); console.log(` 📡 Socket ID: ${socket.id}`); console.log(` 🚀 传输方式: ${socket.io.engine.transport.name}`); console.log(` 🔗 实际URL: ${socket.io.uri}`); socket.disconnect(); resolve({ success: true, transport: socket.io.engine.transport.name, actualUrl: socket.io.uri }); } }); socket.on('connect_error', (error) => { if (!resolved) { resolved = true; clearTimeout(timeout); console.log(` ❌ 连接失败: ${error.message}`); console.log(` 🔍 错误类型: ${error.type || 'unknown'}`); resolve({ success: false, error: error.message, type: error.type }); } }); }); } async function runProtocolTests() { const tests = [ { name: 'WS协议 (错误方式)', url: 'ws://whaletownend.xinghangee.icu/game', options: { transports: ['websocket'], timeout: 5000 } }, { name: 'WSS协议 (直接指定)', url: 'wss://whaletownend.xinghangee.icu/game', options: { transports: ['websocket'], timeout: 5000 } }, { name: 'HTTPS协议 (推荐方式)', url: 'https://whaletownend.xinghangee.icu/game', options: { transports: ['websocket', 'polling'], timeout: 5000 } }, { name: 'HTTP协议 (本地测试)', url: 'http://localhost:3000/game', options: { transports: ['websocket', 'polling'], timeout: 5000 } } ]; const results = []; for (const test of tests) { const result = await testProtocol(test.name, test.url, test.options); results.push({ ...test, result }); // 等待1秒再测试下一个 await new Promise(resolve => setTimeout(resolve, 1000)); } console.log('\n' + '='.repeat(50)); console.log('📊 协议测试结果对比'); console.log('='.repeat(50)); results.forEach((test, index) => { const status = test.result.success ? '✅ 成功' : '❌ 失败'; const transport = test.result.transport ? ` (${test.result.transport})` : ''; const error = test.result.error ? ` - ${test.result.error}` : ''; console.log(`${index + 1}. ${test.name}: ${status}${transport}${error}`); if (test.result.actualUrl) { console.log(` 实际连接: ${test.result.actualUrl}`); } }); console.log('\n💡 协议选择建议:'); console.log('✅ 推荐: 使用 https:// 让Socket.IO自动处理协议选择'); console.log('⚠️ 避免: 直接使用 ws:// 或 wss://,容易出错'); console.log('🔧 本地: 使用 http:// 进行本地开发测试'); console.log('\n📚 协议说明:'); console.log('• ws:// - WebSocket over HTTP (明文传输)'); console.log('• wss:// - WebSocket over HTTPS (加密传输)'); console.log('• http:// → Socket.IO自动选择 ws:// 或 polling'); console.log('• https:// → Socket.IO自动选择 wss:// 或 polling'); process.exit(0); } runProtocolTests().catch(console.error);