Simple WebSocket & NodeJS Server Example

I’ve been searching for a NodeJS server for web sockets, but socket.io, required both the client and server to be run from within node. I wanted to connect to this server via a normal web page using WebSockets from HTML5. Here’s some code, hope you find it useful:

https://github.com/scottpreston/examples

Server Code

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 3000});

wss.on('connection', function (ws) {
    ws.on('message', function (message) {
        console.log('received: %s', message);
        ws.send(message + "!!!!");
    });
});

Client Code

    var websocket = new WebSocket('ws://localhost:3000');
    websocket.onopen = function (evt) {
        websocket.send("This Rocks!");
        websocket.close();
     }
    websocket.onmessage = function (evt) {
        console.log('RESPONSE: ' + evt.data);
    };

 

Scroll to Top