Websocket错误:WebSocket握手期间出错:状态行中未找到响应代码

时间:2014-05-28 18:31:47

标签: javascript node.js websocket

我想与我的服务器建立TCP连接。 但我每次都得到错误......

  

与'ws://my.ip:1337 /'的WebSocket连接失败:WebSocket握手期间出错:状态行中未找到响应代码:回显服务器

客户端:

 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');

怎么了?

1 个答案:

答案 0 :(得分:10)

net.createServer创建普通TCP服务器,而不是 websocket服务器。 Websockets使用TCP上的特定协议,普通TCP服务器不遵循该协议。浏览器成功通过TCP进行网络级连接,但是它希望紧跟webocket握手,普通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');
});
相关问题