How I brought Yahoo Chat back to life in 5 hours: Part 2 — The WebSocket

Image for post
Image for post
Hope you didn’t forget about this grainy reference photo!

What is a WebSocket?

WebSocket Server Setup

mkdir chatroom-backend
cd chatroom-backend
yarn add ws
touch server.js
//server.jsconst WebSocket = require('ws');
const socket = new WebSocket.Server({ port: 3030 });
socket.on('connection', ws => {
ws.on('message', data => {
socket.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(data)
}
})
})
})

Adding The Server Event Listeners

//TextBox.jssocket = new WebSocket('ws://localhost:3030')
Image for post
Image for post
Component Layout (just in case you forgot!)
//TextBox.js//send message to the WebSocket
this.socket.send(JSON.stringify(messageObject))
//TextBox.jscomponentDidMount() {
this.socket.onopen = () => {
//sends username to server for welcome message
this.socket.send(JSON.stringify(this.props.username))
}
this.socket.onmessage = (e) => {
const message = JSON.parse(e.data)
//this came from dispatchStateToProps
this.props.handleNewMessage(message, this.props.messages, this.props.users)
}
this.socket.onclose = () => {
//attempts to reconnect to server if disconnected on error
this.setState({
socket: new WebSocket('ws://localhost:3030'),
})
this.props.handleClose(this.props.users, this.props.username)
}
}

The Final Result

Image for post
Image for post
From NewUser377’s POV
Image for post
Image for post
From NewUser839’s POV

How to Start Up Your WebSocket

cd chatroom-frontend
yarn start
cd chatroom-backend
node server.js

Full-Stack Developer, Software Engineer, and UX/UI Aficionado

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