-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
57 lines (43 loc) · 1.71 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
const path = require('path');
const http = require('http');
const express = require('express');
const SocketIO = require('socket.io');
const formatMessage = require('./utils/messages');
const { userJoinsRoom, getUser, leaveUser, getRoomUsers } = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = SocketIO(server);
app.use(express.static(path.join(__dirname, 'public')));
const port = process.env.PORT || 3000;
io.on('connection', function (socket) {
socket.on('joinRoom', function ({ username, room }) {
const user = userJoinsRoom(socket.id, username, room);
socket.join(user.room);
socket.emit('message', formatMessage(user.username, `Welcome to the ${user.room}`));
socket
.broadcast
.to(user.room) // emit for the specific room
.emit('message', formatMessage(user.username, `${user.username} has joined to the chat!`));
io.to(user.room).emit('roomInfo', {
room: user.room,
users: getRoomUsers(user.room),
});
});
socket.on('chatMessage', function (text) {
const user = getUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, text));
});
socket.on('disconnect', function () {
const user = leaveUser(socket.id);
if (user) {
io.to(user.room).emit('message', formatMessage(user.username, `${user.username} has left the chat!`));
io.to(user.room).emit('roomInfo', {
room: user.room,
users: getRoomUsers(user.room),
});
}
});
});
server.listen(port, function () {
console.log("Server started on port " + port + " !!!");
});