Jump to content
chain

Node.js HTML5 Websocket Example

Recommended Posts

  • Administrators

Below is a very simple example of how to create a basic websocket using node.js. Websockets are great for maintaining a server/client relationship without as much of the overhead of HTTP web traffic. Today, websockets are used to build a magnitude of browser-based real-time applications (live chats, multiplayer games). Basically it's a persistent connection between the server and client in which both applications can send data. Typically, long-polling or Flash have been used as alternatives.

First, you'll need to install the "websocket" package using the Node Package Manager.

 
 
 
 
1
npm install websocket
 
 

You may get an error about the Native code not compiling. (attow) I haven't looked into how to resolve that but the websocket package typically still works. Next we'll setup the server and client. Using the javascript below as a basic skeleton, you'll want to start the server just as any other node snippet. In our example, the server will listen for connections and reply "hello" (to any and everything the client sends) then another message shortly after.

ar server = require('websocket').server, http = require('http');

var socket = new server({
    httpServer: http.createServer().listen(1337)
});

socket.on('request', function(request) {
    var connection = request.accept(null, request.origin);

    connection.on('message', function(message) {
        console.log(message.utf8Data);
        connection.sendUTF('hello');
        setTimeout(function() {
            connection.sendUTF('this is a websocket example');
        }, 1000);
    });

    connection.on('close', function(connection) {
        console.log('connection closed');
    });
}); 

 

Once the server has been started, you can use the code below in any HTML5 browser (that carries websocket support) to establish a connection to the server. In this example, the client sends a "hello" message when it opens the connection and puts anything it receives into the #content div.

<div id="content"></div>

<script type="text/javascript">
    var content = document.getElementById('content');
    var socket = new WebSocket('ws://localhost:1337');
    socket.onopen = function () {
        socket.send('hello from the client');
    };

    socket.onmessage = function (message) {
        content.innerHTML += message.data +'<br />';
    };

    socket.onerror = function (error) {
        console.log('WebSocket error: ' + error);
    };
</script>

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...


×
×
  • Create New...