Node.js HTML5 Websocket Example

Sean Wragg
Sep 14, 2013 · 1 min read

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 npm.

$ 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.

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.


Code, Comics, and Fhqwhgads!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store