This repository has been archived by the owner on Mar 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
63 lines (47 loc) · 1.5 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
var express = require('express');
var cors = require('cors');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(cors());
server.listen(3001);
const chatSocket = io.of('/chat');
const roomsSocket = io.of('/rooms');
var usernames = {};
var rooms = {};
roomsSocket.on('connection', function(socket) {
socket.emit('update', rooms);
});
chatSocket.on('connection', function (socket) {
socket.on('create', function(username, room) {
usernames[username] = username;
rooms[room] = room;
socket.username = username;
socket.room = room;
socket.join(room);
roomsSocket.emit('update', rooms);
console.log('New room: ' + room + ', Created by: ' + username);
socket.emit('update', 'SERVER', 'You created new room: ' + room);
});
socket.on('join', function(username, room) {
if (room in rooms) {
usernames[username] = username;
socket.username = username;
socket.room = room;
socket.join(room);
console.log(username + ' has connected to ' + room);
socket.emit('update', 'SERVER', 'You have connected to: ' + room);
socket.broadcast.to(room).emit('update', 'SERVER', username + ' has connected to ' + room);
} else {
console.log('Room not founded: ' + room);
}
});
socket.on('send', function (data) {
chatSocket.in(socket.room).emit('update', socket.username, data);
});
socket.on('disconnect', function() {
delete usernames[socket.username];
socket.leave(socket.room);
});
});