This is a chat app thet has been implemented using socket.io. Socket io implements websockets to ensure that it keeps an open communication between the server and the client.
- send messages after login
- Notify all users in a room after a user joun a room
- user can communicate with other users in a room
- All users in a room notified when a user leaves a room
- The app aly allows users to join a certain number of rooms
- The data is stored in an array hence can only be accessed when the user logs into the app. Database access features can be added to the app.
Install express
mpm install express
Express setup
const path = require('path')
const http = require('http')
const express = require('express')
const server = http.createServer(app)
const port = process.env.PORT || 5000
server.listen(port, () => console.log(`Server is listening on port ${port}...`))
Access the public folder in the app
app.use(express.static(path.join(__dirname, 'public')))
Install socket.io
npm install socket.io
Importing to express
const socketio = require('socket.io')
const io = socketio(server)
To start a connection
io.on('connection', (socket) => {})
To send a message to the client. Sends message the client only
socket.emit('message', formatMessage(bot, 'Welcome to the chat app'))
Sends the message to the all the have joined except the current user
socket.broadcast.emit(
'message',
formatMessage(bot, `${user.username} has joined the chat`)
)
Sends Message to all users theat are in the current connection
io.emit()
To join a room use
socket.join(roomName)
socket.broadcast
.to(user.room)
.emit('message', formatMessage(bot, `${user.username} has joined the chat`))
socket.on('disconnect', () => {})
Add script tags to htm
<script src="/socket.io/socket.io.js"></script>
To receive message fom the server
socket.on('message', (message) => {
outPutMessage(message)
})