-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
44 lines (34 loc) · 970 Bytes
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const port = 4001;
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
let userCount = 1;
//on user connection
io.on("connection", (socket) => {
userCount++;
let userName;
if (socket.handshake.query.user) userName = socket.handshake.query.user;
else userName = "Guest " + userCount;
socket.emit("SET_USERNAME", userName);
io.sockets.emit("CREATE_MESSAGE", {
content: `${userName} has been connected`,
});
//user send message
socket.on("SEND_MESSAGE", (message) => {
io.sockets.emit("CREATE_MESSAGE", message);
});
//user log out
socket.on("disconnect", () => {
userCount--;
io.sockets.emit("CREATE_MESSAGE", {
content: `${userName} has been disconnected`,
});
});
});
//start server listening
server.listen(port, () => {
console.log("listening on " + port);
});