-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
69 lines (49 loc) · 1.51 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
const express = require('express');
test = express();
const http = require('http');
const ws = require('ws');
const cors = require('cors');
const server = http.createServer(test);
let users = [] // массив хранящий активных юзеров
let messages =[] // массив хранящий историю сообщений
test.use(cors());
let defaultMsg = {
author: 'Admin',
text: 'Welcome to the chat, please enter your nickname!'
}
messages[0] = defaultMsg;
server.listen(3000, () => console.log("Server started"));
test.get('/history', function(req, res) {
var json = JSON.stringify({type: 'history', data: messages});
res.send(json);
})
let wsServer = new ws.Server({
server: server
});
wsServer.on('connection', function(socket) {
let user = {
connection: socket,
userName: ''
}
users.push(user);
socket.on('message', function(message) {
if (user.userName === '') {
user.userName = message;
} else {
var obj = {
text: message,
author: user.userName
}
console.log(obj.author + ": " + obj.text);
messages.push(obj);
var json = JSON.stringify({ type: 'message', data: obj});
for (let u of users) {
u.connection.send(json);
}
}
})
socket.on('close', function() {
let id = users.indexOf(user);
users.splice(id, 1);
});
});