use*_*389 7 javascript websocket node.js
我想与我的服务器建立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
};
Run Code Online (Sandbox Code Playgroud)
服务器:
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');
Run Code Online (Sandbox Code Playgroud)
怎么了 ?
aps*_*ers 10
net.createServer创建一个普通的TCP服务器,而不是websocket服务器.Websockets使用TCP上的特定协议,普通TCP服务器不遵循该协议.浏览器成功通过TCP进行网络级连接,但随后希望立即跟随websocket握手,普通TCP服务器不知道如何提供.
要让Node.js服务器侦听websocket连接,请使用以下ws模块:
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');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7376 次 |
| 最近记录: |