Create a multiplayer game with React and socket.io

the tech stack behind graceless.city

Nicola Gnecchi
2 min readJan 2, 2017

React can be a good choice for creating a web based game, especially for a turn based or a board one. Its declarative approach suits perfectly with this kind of games.

We managed to create a simple game called graceless.city in few days bootstrapping a react client with react-create-app and using socket.io with node.js on the server. The idea behind is fairly simple, it consists of a turn based game in which all players should make their move within 5 seconds. Every turn the players positions are updated and the players can make their next move.

You can try the game here.
You can have a look at the source code here.

Server with node.js and socket.io

Working with socket.io is really satisfying: with few lines of code you’re ready to communicate in real-time with the clients.

The server keeps a list of the players connected and listens to upcoming messages. The players, mapped on a grid, send their next move via the channel. The server, every 5 seconds, updates all the players positions and broadcast them to the clients.

Another tool we’d like to suggest is artillery, it makes so easy to stress test a socket.io environment.

Client with React

Create React App can be installed with npm and it’s great for bootstrapping a React app without configuration. Package.json will contain just one dependency and few scripts. It will take care of Babel, ESLint and webpack for us.

When a user joins the game via the web app, we open a socket connection and we get notified every 5 seconds of the updated players positions. We use leaflet.js in conjunction with React to place the players upon a map. Every time we receive new data, setting the state, we cause React to re-render the players on the grid, so that they can make another move.

Conclusion

We had super fun developing graceless.city! We had a first prototype working in a really short time that can handle many concurrent players. React declarative approach makes very ease to reason about a board game. Socket.io takes care of the real-time communication in a fast and reliable way, yet keeping the code clean and simple.

nik & giusfalco

--

--