This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
87115d2
commit d5b978b
Showing
2 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,5 @@ | ||
# NPM modules | ||
/node_modules | ||
/node_modules | ||
|
||
# NPM cache | ||
package-lock.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
const path = require('path'); | ||
const helmet = require('helmet'); | ||
const http = require('http'); | ||
const socketIoServer = require('socket.io'); | ||
const express = require('express'); | ||
|
||
const PORT = parseInt(process.env.PORT) || 3000; | ||
|
||
const EV_CONNECT = 'connection'; | ||
const EV_MESSAGE = 'message'; | ||
const EV_CHAT_MESSAGE = 'chat_message'; | ||
const EV_DISCONNECT = 'disconnect'; | ||
|
||
const app = express(); | ||
const server = http.createServer(app); | ||
const io = socketIoServer(server); | ||
|
||
// Express middlewares | ||
app.use(helmet()); | ||
app.use(express.static(path.join(__dirname, 'public'))); | ||
|
||
// Listen for socket connections | ||
io.on(EV_CONNECT, (socket) => { | ||
console.log(`client socket ${socket.id} connected`); | ||
|
||
// Welcome the new user | ||
socket.emit(EV_MESSAGE, 'Welcome to NoChat!'); | ||
|
||
// Send to all users except the new user | ||
socket.broadcast.emit(EV_MESSAGE, 'A user has joined the chat.'); | ||
|
||
// When a user disconnects | ||
socket.on(EV_DISCONNECT, () => { | ||
io.emit(EV_MESSAGE, 'A user has left the chat.'); | ||
}); | ||
|
||
// When a user sends a message | ||
socket.on(EV_CHAT_MESSAGE, (message) => { | ||
// We broadcast it to every user | ||
io.emit(EV_MESSAGE, message); | ||
}); | ||
}); | ||
|
||
// Start Express server | ||
server.listen(PORT, () => { | ||
console.log(`listening on port ${PORT}`); | ||
}); |