-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
79 lines (67 loc) · 2.29 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static("public"));
// Global variables to hold all usernames and rooms created
var usernames = {};
var rooms = [
{ name: "global", creator: "Anonymous" },
{ name: "chess", creator: "Anonymous" },
];
io.on("connection", function (socket) {
console.log(`User connected to server.`);
socket.on("createUser", function (username) {
socket.username = username;
usernames[username] = username;
socket.currentRoom = "global";
socket.join("global");
console.log(`User ${username} created on server successfully.`);
socket.emit("updateChat", "INFO", "You have joined global room");
socket.broadcast
.to("global")
.emit("updateChat", "INFO", username + " has joined global room");
io.sockets.emit("updateUsers", usernames);
socket.emit("updateRooms", rooms, "global");
});
socket.on("sendMessage", function (data) {
io.sockets.to(socket.currentRoom).emit("updateChat", socket.username, data);
});
socket.on("createRoom", function (room) {
if (room != null) {
rooms.push({ name: room, creator: socket.username });
io.sockets.emit("updateRooms", rooms, null);
}
});
socket.on("updateRooms", function (room) {
socket.broadcast
.to(socket.currentRoom)
.emit("updateChat", "INFO", socket.username + " left room");
socket.leave(socket.currentRoom);
socket.currentRoom = room;
socket.join(room);
socket.emit("updateChat", "INFO", "You have joined " + room + " room");
socket.broadcast
.to(room)
.emit(
"updateChat",
"INFO",
socket.username + " has joined " + room + " room"
);
});
socket.on("disconnect", function () {
console.log(`User ${socket.username} disconnected from server.`);
delete usernames[socket.username];
io.sockets.emit("updateUsers", usernames);
socket.broadcast.emit(
"updateChat",
"INFO",
socket.username + " has disconnected"
);
});
});
server.listen(5500, function () {
console.log("Listening to port 5500.");
});