Software engineer, data guy, Open Source enthusiast, New Hampshire resident, husband, father. Fan of guitars, hiking, photography, homebrewing, sarcasm.
This is the entirety of the backend, new file: backend/app.js. This app handles the socket events for connection, disconnection, and sending/receiving of messages. More documentation about Socket.IO can be found here.
To start the backend, execute: node app.js
Next I scaffolded the frontend.
Include the Bootstrap CSS from CDN by adding the stylesheet before the closing </head> tag in frontend/src/index.html:
I revised the main React component to include a Chat component. Edited file: frontend/src/components/Main.js:
Below is the main Chat component (file: frontend/src/components/Chat.js). The render method conditionally: a) displays a ChatName form, for a user to enter their name and join the chat; or b) shows the ChatRoom component which allows them to send and receive messages. The ChatName component handles the submission of the user name by passing a callback (handleSubmitName) as a “prop” to the component.
Here is the ChatName component which uses React-Bootstrap components to build a simple form (file: frontend/src/components/ChatName.js). As the user types into the Name text input, an onChange callback is used to set the state of the component (this.setName). When the form is submitted, the props callback is used to propagate changes to the parent Chat component.
After the user has entered their name, the state change causes the render method to remove the ChatName form, and display the ChatRoom component. In the component constructor, a new socket is established to the backend. When the component is mounted (componentDidMount), the user is subscribed to “chat” messages (this.socket.on('chat'...), and when the socket receives new messages, they are pushed to component state. When the user enters a message and submits the form, the message (user name, message, and a timestamp) is sent as JSON to the backend (this.socket.emit('chat'...). Contents of file frontend/src/components/ChatRoom.js:
All received messages are stored in the Chat component state, and passed to the ChatTable component as a prop to be rendered. Contents of file: frontend/src/components/ChatTable.js
In addition, I added a bit of CSS to format the tabular layout. file: frontend/src/components/Chat.css
The frontend can be started via: npm start, and accessible at http://localhost:8000. I opened two browser windows/tabs to test:
To integrate these services with a simple Docker Compose configuration: