Reputation: 83
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 ?
Upvotes: 7
Views: 8174
Reputation: 115940
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');
});
Upvotes: 10