-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (62 loc) · 2.05 KB
/
server.js
File metadata and controls
80 lines (62 loc) · 2.05 KB
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
80
const http = require('http')
const express = require('express')
// const { listen } = require('socket.io')
const app = express()
const SERVER_PORT = process.env.PORT || 3344
const socketio = require('socket.io')
const server = http.createServer(app)
const io = socketio(server)
let users = {
Amit: 'Amit123',
}
let socketMap = {}
io.on('connection',(socket)=>{
console.log('connected with socket id =', socket.id)
function login(s, u) {
s.join(u)
s.emit('logged_in')
socketMap[s.id] = u
console.log(socketMap)
}
socket.on('login', (data) => {
if (users[data.username]) {
if (users[data.username] == data.password) {
login(socket, data.username)
} else {
socket.emit('login_failed')
}
} else {
users[data.username] = data.password
login(socket, data.username)
}
})
socket.on('msg_send',(data)=>{
data.from = socketMap[socket.id]
if (data.to) {
io.to(data.to).emit('msg_rcvd', data)
} else {
socket.broadcast.emit('msg_rcvd', data)
}
})
//------Socket websocket theory of sending msg--------
// socket.broadcast.emit('msg_rcvd',data)
// // -- this line will actually work for a chatting app that means will send that msg to every socket(user) except current one.
// // console.log('received',data.msg) -- this line is for reading msg on server
// // socket.emit('msg_rcvd',data)-- this only send data to single particular msg itself
// // io.emit('msg_rcvd',data) -- but io.emit sends data to every person connected to that server
// })
// socket.on('boom',()=>{
// console.log('boom received from',socket.id)
// })
// setInterval(()=>{
// socket.emit('whizz')
// },2000)
console.log("Socket created :" + socket.id)
socket.on('play', function(data) {
io.emit('play', data)
})
})
app.use('/',express.static(__dirname+'/public'))
server.listen(SERVER_PORT,()=>{
console.log("server started at http://localhost:3344")
})