最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Websocket Error: Error during WebSocket handshake: No response code found in status line - Stack Overflow

programmeradmin0浏览0评论

I want to make a tcp connection to my server. But i get en error everytime...

WebSocket connection to 'ws://my.ip:1337/' failed: Error during WebSocket handshake: No response code found in status line: Echo server

Client:

 var connection = new WebSocket('ws://my.ip:1337'); 
 connection.onopen = function () {
 connection.send('Ping'); // Send the message 'Ping' to the server
 };

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

Whats wrong ?

I want to make a tcp connection to my server. But i get en error everytime...

WebSocket connection to 'ws://my.ip:1337/' failed: Error during WebSocket handshake: No response code found in status line: Echo server

Client:

 var connection = new WebSocket('ws://my.ip:1337'); 
 connection.onopen = function () {
 connection.send('Ping'); // Send the message 'Ping' to the server
 };

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

Whats wrong ?

Share Improve this question edited May 28, 2014 at 18:55 apsillers 116k18 gold badges247 silver badges247 bronze badges asked May 28, 2014 at 18:31 user3524389user3524389 831 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

net.createServer creates a plain TCP server, not a websocket server. Websockets use a specific protocol over TCP, which a plain TCP server does not follow. The browser successfully makes a network-level connect over TCP, but it then expects a websocket handshake to immediately follow, which the plain TCP server does not know how to provide.

To have your Node.js server listen for websocket connections, use the 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');
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论