-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
65 lines (50 loc) · 1.44 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
64
65
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const PORT = 8080;
const onlineUsers = {};
app.use(express.static('public'));
app.use(bodyParser.json());
app.post('/message', (req, res) => {});
// websocket connection
io.on('connection', (socket) => {
console.log('a connection was made');
// user identification
socket.on('identification', (msg) => {
console.log('ident', msg);
// add socket to onlineUsers object
onlineUsers[msg.id] = socket;
socket.user = msg;
// send back identification verification
socket.emit('verified', true);
io.emit('online', msg.id);
});
// disconnect event
socket.on('disconnect', () => {
const { user } = socket;
if (user && user.id) {
delete onlineUsers[user.id];
io.emit('offline', user.id);
}
console.log('a user disconnected');
});
// user chat message
socket.on('chat', (msg) => {
console.log('chat message:', msg);
// this is where you would save to a DB
// then emit out to other chat members
const intendedUser = onlineUsers[msg.to];
if (intendedUser) {
intendedUser.emit('chat', msg);
}
});
// list of users
socket.on('users', () => {
socket.emit('users', Object.keys(onlineUsers));
});
});
http.listen(PORT, () => {
console.log(`Server started on PORT: ${PORT}`);
});