-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
62 lines (45 loc) · 1.71 KB
/
app.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
var express=require('express')
var app=express()
var socketio=require('socket.io')
var http=require('http')
var {generate}=require('./public/js/messages')
var {addUser,removeUser,getUser,getUsersInRoom}=require('./public/js/users')
var server=http.createServer(app)
app.use(express.static('public'))
var io=socketio(server)
io.on('connection',(socket)=>{
console.log('chat app connected')
socket.on('join',({username,room},callback)=>{
var userdata=addUser({id:socket.id,username,room})
if(userdata.error)
{
return callback(userdata.error)
}
socket.join(userdata.user.room)
socket.emit('message',generate('welcome','Server'))
socket.broadcast.to(userdata.user.room).emit('message',generate(`${userdata.user.username} has joined`,'Server'))
})
// socket.emit('message',generate('welcome'))
// socket.broadcast.emit('message',generate('A new user joined'))
socket.on('reply',(msg,callback)=>{
var user=getUser(socket.id)
io.to(user.room).emit('message',generate(msg,user.username))
callback()
})
socket.on('location',(livelocation,callback)=>{
var user=getUser(socket.id)
io.to(user.room).emit('locationMessage',generate(livelocation,user.username))
callback()
})
socket.on('disconnect',()=>{
var user=removeUser(socket.id)
// the returned value is either user data or undefined
if(user)
{
io.to(user.room).emit('message',generate(`${user.username} left the chat room`,'Server'))
}
})
})
server.listen(3001,()=>{
console.log('server started')
})