Chat with WebSockets — Server and Client both in NodeJs

Usually when somebody thinks chat, they think WebSockets. Normally there are tutorials how you make a server in NodeJs for example and a client in HTML. But in this case the client will also be a NodeJs app. It will display messages from the server and listen to users input with NodeJs readline.

Photo by Pavan Trikutam on Unsplash

Extra

There will be no persistence here. A client will see only messages that server sends him from the point he connects to it. Also whenever a client is connected, the server will generate a random color and a random name, and the client will use that. It’s not necessary, it’s just a few extra stuff.

Utils — this file contains the generate random color and generate random name. You can check the contents of that file in full on Github. Link at the end of story.

Server

myClient is just a class called Client (not the actual client we are gonna define that connects to the server). It contains 2 fields, name & color.

handleReceviedMsg accepts the message that was send to server, and returns that it’s JSON stringified.

For WebSockets we are using the ws package. And chalk is used to make the console log a little colourful.

First we create the WebSocketServer, running on port 8080, with option for client tracking. This tracking enables that the WebSocket server has clients property.

When the server detects a connection, we create a client instance. It’s just a placeholder for name and color. Then we send the init or welcome message to the client, with that information.

Whenever a new message is received, we will send that message to every client back. Even to the one who has send it. So they know that the message was received and transmitted.

Client

The client connects to the WebSocket server. On initial or welcome message, the server will return the name and the color. The client will use that to display message in color with the help of chalk.

For client input we use nodes readline. Readline listents on the line event. This event is triggered whenever the client presses the Enter key. On that event we capture the text that was inputed and together with the clients name and color we send that to the server.

Everything else should be pretty much self explanatory.

On open is when we have a connection established. On close is when the connection gets terminated. On message is whenever server send us a message.

client.js
server.js

Whole structure and code: https://github.com/zprima/wschat

developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store