Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing node websockets with telnet

I am writing a socket-based server in Node js using the ws library, and I would like to test that my code works. I have seen telnet used elsewhere to test simple chat servers, but when I start my server and execute telnet 127.0.0.1 5000, although the output says "connected to localhost", my server doesn't log anything associated with a new connection. Am I testing my server wrong or is my server simply not working? My server code is below:

    var WebSocketServer = require('ws').Server
      , http = require('http')
      , express = require('express')
      , app = express()
      , port = process.env.PORT || 5000;

    var server = http.createServer(app);
    server.listen(port);

    var wss = new WebSocketServer({server: server});
    console.log('websocket server created');
    wss.on('connection', function(ws) {
    var id = setInterval(function() {
        ws.send(JSON.stringify(new Date()), function() {  });
    }, 1000);

    console.log('websocket connection open');

    ws.on('close', function() {
        console.log('websocket connection close');
        clearInterval(id);
    });
   });
like image 876
user3080098 Avatar asked Jan 11 '14 05:01

user3080098


2 Answers

You connected to HTTP server, but did not established WebSocket connection. That's why your script doesn't print anything.

I'm not sure you can test websocket manually, look at the handshake.

But there are a few telnet-like programs that work with websocket. Maybe wscat from ws module you're using will help with that.

like image 192
alex Avatar answered Sep 21 '22 03:09

alex


I found https://www.websocket.org/echo.html To be useful. Just create a websocket.index file on your hard-drive if you are testing a localhost server. Code is on the bottom of the page.

like image 31
Neoraptor Avatar answered Sep 20 '22 03:09

Neoraptor