Playing around with websockets

January 23, 2021

Some time ago, I came into touch with websockets, and had to familiarize myself with the concept which is quite different from simple HTTP requests / REST.

I decided to write a small project from scratch, using just plain JavaScript and a canvas to make a game and get to know it a little bit better. It looks like this:

Finding each other

Contrary to the stateless protocol REST or HTTP in general, websockets feel like access to an underlying layer, on which one has the freedom to build an own protocol or communications channel.

The first thing is to open a channel on the server and wait for any client to connect to it.

Backend (Python):

# open websocket
server = WebsocketServer(5678, host='127.0.0.1')

# set callback function for new client / received message
server.set_fn_new_client(new_client)
server.set_fn_message_received(message_received)

# functions
def new_client(client, server):
    print "new client! -> ", client['id']

def message_received(client, server, message):
    print "client ", client['id'], " sent: ", message

And in the Frontend (JavaScript):

// open websocket
let socket = new WebSocket("ws://localhost:5678");

// define message handler for incoming messages:
socket.onmessage = (event) => {
  const message = JSON.parse(event.data);
  ...
}

So now if we start server and afterwards the client, we should see an incoming connection on the server:

Defining a protocol

I decided to do all the board logic from the backend, so no game states could be manipulated from the frontend. To start a game, the client would first send a NEW_GAME request, get a board to display, and for each move, it would just point out coordinates to the server (with a REQUEST_MOVE), which then the server would take, validate (only neighbours can be moved) and provide an updated board to the client.

The client doesn't know anything about moving gems or completing three in a row, it just displays whatever the server sends back. Scoring is very simple, if three matching gems are moved in a straight line, the player gets 10 points. The matching gems are then replaced by random new gems, in some fancier games you would see the gems above tumbling down at this point :-)

Full source code is on Github: websocket-example.

Thanks for reading!