Real Time Web App | React.js + Express + Socket.io

All of the clients can emit events to the server, and the server will relay whatever events are received to the rest of the clients.

Socket.io basically works by emitting information from one client of the server to the server, then the server emits that information to the rest of the clients.

After completing a few small scale apps with Socket.io, as well as going through multiple tutorials, I’ve begun to understand what’s actually happening.

Web apps with live user interactions such as chat apps have always excited me. Being able to remotely change what others are able to see is quite exciting, and allows for interesting UX.

NOTE: I recommend writing all of the code by yourself and not copying and pasting. This helps with remembering, and understanding the code. I also recommend testing out the code bits as you write them to see what parts of the overall project they are helping.

In this short course, we will make a basic app that allows you to change the background color with a click of the button on two different windows. This project is brief and only covers the basics of socket.io. By using this boiler-plate however, you could scale your app to a much larger size.

In order to use the tools needed in this course you must have NPM installed on your computer.

Once you have one NPM or yarn if that’s what you prefer, we will need to download my favorite React.js boiler-plate: create-react-app.

First, create the main folder:

mkdir react-socket-app
cd react-socket-app

Next, let’s initiate our folder with NPM:

npm init

This will give you a bunch of options to choose from. Just click enter for each one. Then install the needed packages:

npm install --save express socket.io
// this might take a bit

Node.js + Express Server

Now that we are in our new react app, we need to add a new file:

touch server.js // on OSX or linux

Once we have our server.js file, we should populate it with our express server code. Open your react-socket-app folder in your favorite IDE and edit your server.js file:

react-socket-app/server.js1

So, we are creating a server with http.createServer with the express application as the only argument. Next, we set io to a socket with the instance of our server. Lastly, we set our server to listen on port 4001.

Once we have this, you can test it by running:

node server.js

Should Return:

Listening on port 4001

Use ctrl+c to close the server.

If you go to “http://localhost:4001″, you won’t see anything because this is just the server; we haven’t done the front end of our project yet.

That’s all we’ll add to the server for now. We will connect to this server later on in the front-end in order to transfer sockets.

This is how your app’s folder system should look at this point:

react-socket-app
> node_modules
-package.json
- server.js

React Component

Great! Time to move on to writing the front-end code.

Let’s use create-react-app to create our client folder:

npm install -g create-react-app // if you don't have it already
create-react-app socket-client
cd socket-client

Now let’s look at the socket-client folder:

socket-client
> node_modules
> public
- favicon.ico
- index.html
- manifest.json

> src
- App.css
- App.js
- App.test.js
- index.css
- index.js
- logo.svg
- registerServiceWorker.js

- .gitignore
- package.json
- README.md

We can edit this file structure a bit to look like this:

socket-client
> node_modules
> public
- index.html
- manifest.json

> src
- App.js
- App.test.js
- index.css
- index.js
- registerServiceWorker.js

- .gitignore
- package.json
- README.md

First, we need to install the socket.io-client:

npm install --save socket.io-client

Now, let’s edit our first React.js component, App.js:

react-socket-app/socket-client/src/App.js

Line 6: creates a new component that consists of a div wrapped around a p element.

Line 21: exports “App.js” component so we can import it into the parent component: index.js

This is the basic setup for a react component. To test it, run:

npm start // in your socket-client folder

Your main component: index.js should look like this:

react-socket-app/socket-client/src/index.js

We don’t need to change this because it already imports the “App.js” component on line 4.

Let’s keep writing our “App.js” component:

react-socket-app/socket-client/src/App.js

The first thing we did was add “this.state.endpoint”. And this is the URL of the server; that we are trying to connect to with socket.io. Next, we created a send method that allows us to emit sockets to the server, we will handle those sockets on the server’s side later. We also started listening for socket emits in the render method. This will listen for events from the server and will run the callback function if there is a “change color” event emitted. In the callback function, we simply change the color of our button.

To make sure everything works, go into your socket-client folder and run:

cd socket-client
npm start

This should take you to “localhost:3000” which should look like this:

The button won’t do anything at this point. This is just the front end, we still need to write an event handler for the button that emits a socket to the server.

Lastly, in our “App.js” component, let’s add some color changing functionality!

Add these new lines to your react component:

react-socket-app/socket-client/src/App.js

These buttons will allow the user to choose a color for the background.

Adding Socket.io to the server

Finally, we have to make sure the server is listening for emits from the clients. It also has to emit out any emits it gets from the other clients.

Let’s add some socket.io functionality to our server.js file:

All we do is check for connections on line 17, and if their are any, we listen for events from clients. If we get an event, we just emit the same event to the rest of the clients with whatever argument was given.

For the final app, run:

node server.js // in /react-socket-app

Open another terminal tab and run this as well:

npm start // in /react-socket-app/socket-client

If everything worked, you should be able to open two separate tabs on your browser, and when you click the button on one of the pages; both pages should turn that color.

Also, if you got to the terminal where you have your server open, it should be logging whenever a client connects and disconnects from the socket.

Pretty simple, right?

One more thing, if you want to point your express server to an ngrok tunnel, you just need to run ngrok on port 4001 and it should give you a random url for your express server. You can then share that url with your friend, and you can have live color changes between two different machines.

I hope you learned something about connecting React with socket.io! Feel free to add as much code to this boiler-plate as you want; this is really the bare minimum. And please ask any questions or queries you might have.

source code: https://github.com/averybiskup/medium-react

Disclaimer:

This code is definitely not best practices.

This is my first article. And it is likely very naive.

Avery Biskup

[email protected]