Setting up a simple local web socket server

Published on: January 24, 2023

Every once in a while I find myself writing about or experimenting with web sockets. As an iOS developer, I’m not terribly familiar with setting up and programming servers that leverage web sockets beyond some toy projects in college.

Regardless, I figured that since I have some posts that cover web sockets on my blog, I should show you how I set up the socket servers that I use in those posts. Before you read on, I’m going to need you to promise me you won’t take the code I’m about to show you to a production environment…

You promise? Good.

I generally use the [WebSocket (or ws) package from npm]( along with node.js. I chose these technologies because that’s what was around when I first learned about web sockets, and because it works well for my needs. If you prefer different tools and languages that’s perfectly fine of course; I just won’t cover them on here.

Once you have node installed on your machine (go here if you haven’t already installed node.js) you can create a new folder somewhere on your machine, and navigate to that folder in your terminal. Then type npm install ws to install the ws package in your current directory (so make sure you’re in your project folder when typing this!).

After that, create a file called index.mjs (that’s not a typo; it’s a fancy new JavaScript module extension) and add the following contents to it:

import WebSocket, { WebSocketServer } from 'ws';

const wss = new WebSocketServer({port: 8080});

Usually when I’m experimenting I like to do something simple like:

  • For a new connection, start listening for incoming messages and do something in response; for example, close the connection.
  • Send a “connection received” message
  • Send a new message every second
  • When the received connection is closed, stop sending messages over the socket (nobody is listening anymore)

The code to do this looks a bit as follows:

const wss = new WebSocketServer({port: 8080});

wss.on('connection', function connection(wss) {
    wss.on('message', function message(data) {
        console.log('received %s', data);

    wss.send('connection received');

    var t = setInterval(function() {
        console.log("sending message");
        wss.send('sending message!');
    }, 1000);

    wss.on('close', function close() {
        console.log("received close");

Again, I’m not a professional JavaScript developer so there might be much nicer ways to do the above but this is what works for the purposes I tend to use web sockets for which is always purely experimental.

For a full overview of web socket events that you might want to add handlers for, I highly recommend you take a look at the docs for ws.


Quick Tip

Subscribe to my newsletter