-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
57 lines (40 loc) · 1.55 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
var express = require("express");
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var usernames = {};
var rooms = ['room1','room2','room3'];
io.sockets.on('connection', function (socket) {
socket.on('adduser', function(username){
socket.username = username;
socket.room = 'room1';
usernames[username] = username;
socket.join('room1');
socket.emit('updatechat', 'SERVER', 'you have connected to room1');
socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
socket.emit('updaterooms', rooms, 'room1');
});
socket.on('sendchat', function (data) {
io.sockets.in(socket.room).emit('updatechat', socket.username, data);
});
socket.on('switchRoom', function(newroom){
socket.leave(socket.room);
socket.join(newroom);
socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
socket.emit('updaterooms', rooms, newroom);
});
socket.on('disconnect', function(){
delete usernames[socket.username];
io.sockets.emit('updateusers', usernames);
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
});