-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
158 lines (128 loc) · 3.77 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
const path = require('path');
const express = require('express');
const compression = require('compression');
const WebSocket = require('ws');
// const { ExpressPeerServer } = require('peer');
const { getFullIpAddress, getNetworkAddress } = require('./utils/network');
const app = express();
app.use(compression({ memLevel: 9 }));
const PORT = process.env.PORT || 5000;
const httpServer = app.listen(PORT, () => {
console.log('Server start on port:', PORT);
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
// Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// API endpoint
app.use('/api/socket', require('./routes/socketRoute'));
app.use('/api/send', require('./routes/sendRoute'));
app.use('/api/folder', require('./routes/folderRoute'));
// // PeerJS path
// const peerServer = ExpressPeerServer(httpServer);
// app.use('/api', peerServer);
// Server static files
app.use(express.static('client/build'));
// Handle URL
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client/build/index.html'));
});
// WebSocket Server
const wss = new WebSocket.Server({ server: httpServer });
wss.setMaxListeners(0);
const clients = {};
wss.on('connection', (ws, req) => {
console.log(`Full IP address: ${getFullIpAddress(req)}`);
console.log(`Network address: ${getNetworkAddress(req)}`);
// Recieve message from client
ws.on('message', (message) => {
const data = JSON.parse(message.toString());
// Should happen once in the app startup
if (data.type === 'connect') {
ws.userAgent = data.userAgent;
ws.userId = data.userId;
ws.networkAddress = data.networkAddress;
clients[ws.userId] = ws;
sendUsersInSameNetwork(wss, ws);
}
// Get list of users in same network
else if (data.type === 'network') {
sendUsersInSameNetwork(wss, ws);
}
// Client in room
else if (data.type === 'room') {
ws.userId = data.userId;
clients[ws.userId] = ws;
}
// Client disconnect
else if (data.type === 'disconnect') {
delete clients[data.userId];
}
// Handle message from client
else if (data.type === 'message') {
// Send message to room except the sender
// sendToRoom(wss, ws, data);
// Send message to specific client
sendToClient(data.userId, data);
}
});
ws.on('close', () => {
delete clients[ws.userId];
sendUsersInSameNetwork(wss, ws);
});
ws.on('error', (err) => {
console.error(`ERROR: ${err}`);
});
});
function sendToClient(clientId, data) {
const client = clients[clientId];
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
}
function sendToRoom(wss, ws, data) {
wss.clients.forEach((client) => {
if (
client !== ws &&
client.readyState === WebSocket.OPEN &&
client.roomId === data.roomId
) {
client.send(JSON.stringify(data));
}
});
}
function sendUsersInSameNetwork(wss, ws) {
const params = {
action: 'network',
networkAddress: ws.networkAddress,
users: [],
};
for (const [key, value] of Object.entries(clients)) {
if (value.networkAddress === ws.networkAddress) {
const userDetail = {
userAgent: value.userAgent,
userId: value.userId,
};
params.users.push(userDetail);
}
}
wss.clients.forEach((client) => {
if (
client.readyState === WebSocket.OPEN &&
client.networkAddress === ws.networkAddress
) {
client.send(JSON.stringify(params));
}
});
}
// // PeerJS Server
// peerServer.connect()
// peerServer.on('connection', (client) => {
// console.log(`Client connected: ${client.getId()}`);
// });
// peerServer.on('error', (err) => {
// console.error(`ERROR: ${err}`);
// });