我想与我的服务器建立一个 tcp 连接。 但是我每次都会出错...
WebSocket connection to 'ws://my.ip:1337/' failed: Error during WebSocket handshake: No response code found in status line: Echo server
客户:
var connection = new WebSocket('ws://my.ip:1337');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
服务器:
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
console.log('request');
});
server.listen(1337, 'my.ip');
怎么了?
最佳答案
net.createServer
创建一个纯 TCP 服务器,而不是 websocket 服务器。 Websockets 使用基于 TCP 的特定协议(protocol),普通 TCP 服务器不遵循该协议(protocol)。浏览器成功地通过 TCP 建立了网络级连接,但它随后希望立即进行 websocket 握手,而普通 TCP 服务器不知道如何提供。
要让您的 Node.js 服务器监听 websocket 连接,请使用 ws
module :
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 1337});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
ws.send('this is an echo response; you just said: ' + message);
});
ws.send('send this message on connect');
});
关于javascript - Websocket 错误 : Error during WebSocket handshake: No response code found in status line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23919273/