-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
59 lines (53 loc) · 1.49 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
const WebSocket = require('ws');
const Cloudinary = require('cloudinary');
const wss = new WebSocket.Server({port: 8080}, () => {
console.log('Server started...');
});
let ws;
let clients = {};
wss.on('connection', (server) => {
ws = server;
const client = ws.upgradeReq.headers['sec-websocket-key'];
clients[client] = ws;
ws.on('message', (msg, data) => receive(msg, data, client));
ws.on('close', (socket, number, reason) =>
console.log('Closed: ', client, socket, number, reason),
);
});
const send = (msg, client) => {
console.log('Sending: ', msg);
clients[client].send(JSON.stringify(msg), (error) => {
if (error) {
delete clients[client];
} else {
console.log(`Sent: ${msg}, to ${client}`);
}
});
};
const receive = (msg, data, sender) => {
console.log(`Received: ${msg.substring(0, 500)}, from ${sender}`);
broadcast(msg, sender);
};
const broadcast = (msg, sender) => {
msg = JSON.parse(msg);
Object.keys(clients).map((client) => {
if (client === sender) {
return;
} else if (msg.image !== undefined) {
Cloudinary.v2.uploader.unsigned_upload(
`data:image/jpeg;base64,${msg.image}`,
'myPreset',
{cloud_name: 'zafer'},
(_err, result) => {
console.log('Uploaded URL: ' + result.url);
msg.image = result.url;
msg.text = undefined;
msg.timestamp = new Date().getTime();
send(msg, client);
},
);
} else {
send(msg, client);
}
});
};