#8 Trying out Node.js & WebSockets
- Aaron
- Nov 28, 2020
- 2 min read
Updated: Dec 2, 2020
In the last article, I talked about creating a simple card game.
Let's try to add some multiplayer functionality with express and socket.io
Because I want real-time communication in my game, I made the choice to use WebSockets (Socket.io).
There are some other real-time communication alternatives: Pusher for example.
To make my development life easier, I will use Express, the node.js framework. (Other node frameworks who you might want to look into are: Sails.js, Fastify, and Colyseus)
I plan to NOT save my game states on a database. If I use a database, I want to only save the outcome of the game to a database. Why? Databases are expensive or get expensive really quick, and the scale of this project does not really require it.
I began by adding a real-time chat first, so I could test Socket.io and node.js somewhat. Learning a bit about Handshakes, broadcasting, etc... in the process.
It currently looks like this:

The user first enters his (unique) name, and then they will be able to send a message in real-time. Everyone connected to the website will then see that same message with a timestamp.
Things that still need to be added:
Some code will need to be executed on the server
value map
distribute and shuffle cards
Check if the card send by the client is valid
Calculate winners
Code changes
Replace computer with the player(s)
Try rooms
Turn-based
Steps
The user enters the homepage
The user creates or joins a new room
Wait for others to arrive before starting the game
Rotating turns
Handling the winner/loser
Handling player exits in-game
Check out the GitHub repo:
The deployment process
I then started looking for a platform to host my server on.
Netlify
Usually, I like to host my websites with Netlify. But Netlify is a Jamstack service and does not support node.js.
Vercel
I somewhere heard that Vercel supported node.js, so I tried to deploy with Vercel.

Vercel works with Serverless functions, and serverless functions do not support WebSockets 😞 (I would have to look for third party solutions to combine with Vercel. Vercel can be combined with other services to handle WebSockets without having to literally host them). In this case, I was looking for a place to host my server, so I kept looking for another solution. I could still use Vercel to deploy my front-end though.
Heroku
To Heroku, we go! You can easily host an HTTP server with Heroku.
Just make sure you have not reached your 5 app limit! 😅

Deployment with Heroku was very straightforward.
Just connect your GitHub repo.
You can view the online demo: https://demo-multiplayer-highcard.herokuapp.com/
To be continued...
Comentários