javascript - Websocket 错误 : Error during WebSocket handshake: No response code found in status line

标签 javascript node.js websocket

我想与我的服务器建立一个 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/

相关文章:

javascript - javascript 命令行参数和映射

javascript - javascript socket io可以监听unix sock吗?

java - Tomcat WebSocket 错误

Java (Android) WebSocket 客户端库

javascript - 如何使用 setTimeout、setInterval 或循环显示?

javascript - jQuery 函数返回谷歌地图缩放级别

javascript - 从 Javascript 调用 php 函数的最简单方法是什么?

javascript - ApostropeCMS - 在快速 route 渲染完整的 HTML 页面

node.js - EC2 托管的 Node.js 应用程序 - 无法远程连接到端口

javascript - 如何解决获取json对象元素的问题