Skip to content

Commit dea0374

Browse files
committed
ws comments and fixes
1 parent df93103 commit dea0374

File tree

4 files changed

+72
-41
lines changed

4 files changed

+72
-41
lines changed

client/src/Hooks/useDebouncedFunction.hook.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@ import { useEffect, useReducer } from 'react';
88
*/
99
function useDebouncedFunction(callback, delayms) {
1010
const [state, debounced] = useReducer((state, arg) => {
11-
return { count: state.count++, arg: arg }
11+
return { count: state.count + 1, arg: arg }
1212
}, { count: 0, arg: undefined })
1313
useEffect(() => {
14-
const handler = setTimeout(() => callback(state.arg), delayms)
14+
const handler = setTimeout(() => {
15+
if (state.count) callback(state.arg)
16+
}, delayms)
1517
return () => clearTimeout(handler)
1618
// eslint-disable-next-line react-hooks/exhaustive-deps
1719
}, [state])

client/src/Hooks/useUpdaterSocket.hook.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ const WS_PORT = process.env.WS_PORT || 3030
1313
*/
1414
function useUpdaterSocket(updateData, auth) {
1515
const { request } = useHttp()
16+
17+
/**дебонсированный обработчик входящего обновления */
18+
const debouncedUpdate = useDebouncedFunction(updateData, 200)
19+
20+
/**колбек для получения url сокета */
1621
const getSocketUrl = useCallback(async () => {
1722
return new Promise(resolve => {
1823
request("/getIp")
@@ -27,15 +32,14 @@ function useUpdaterSocket(updateData, auth) {
2732
// eslint-disable-next-line react-hooks/exhaustive-deps
2833
}, [])
2934

30-
const debouncedUpdate = useDebouncedFunction(updateData, 200)
31-
35+
/**опции обработки событий сокета */
3236
const socketOptions = {
3337
onOpen: (e) => {
3438
sendRegisterMsg()
3539
console.log("ws open")
3640
},
3741
onClose: (e) => {
38-
console.log("ws close")
42+
console.error("ws close")
3943
},
4044
onMessage: (e) => {
4145
console.log("ws update message")
@@ -46,22 +50,27 @@ function useUpdaterSocket(updateData, auth) {
4650
},
4751
}
4852

53+
/**подключение WebSocket */
4954
const { sendMessage } = useWebSocket(getSocketUrl, socketOptions)
5055

51-
const sendMsg = (target) => {
56+
/**дебонсированный обработчик отсылаемого обновления */
57+
const sendUpdateMsgDebounced = useDebouncedFunction(sendUpdateMsg, 200)
58+
59+
/** отпрака сообщения сокета */
60+
function sendMsg(target) {
5261
const msg = JSON.stringify({
5362
userId: auth.userId,
5463
target
5564
})
5665
sendMessage(msg)
5766
}
5867

59-
const sendUpdateMsgDebounced = useDebouncedFunction(sendUpdateMsg, 200)
60-
68+
/**отправка отсылаемого обновления */
6169
function sendUpdateMsg() {
6270
sendMsg("update")
6371
}
6472

73+
/**отпрака сообщения регистрации сокета */
6574
function sendRegisterMsg() {
6675
sendMsg("register")
6776
}

client/src/Pages/NotesPage.js

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,15 @@ function NotesPage() {
7878

7979
/**
8080
* Внесение в полученных данных в массив
81-
* @param {*} notes
81+
* @param {Array<{}>} notes
8282
*/
8383
function setLoadedNotes(notes) {
8484
setNotesArr([...notes])
8585
}
8686

8787
/**
8888
* удаление карточки
89-
* @param {*} id
89+
* @param {string} id
9090
*/
9191
function removeNote(id) {
9292
const index = getNoteIndexById(id)
@@ -97,7 +97,7 @@ function NotesPage() {
9797

9898
/**
9999
* добавление карточки
100-
* @param {*} noteData
100+
* @param {{}} noteData
101101
*/
102102
function addNote(noteData = {}) {
103103
const newId = String(auth.email) + String(Date.now()) + String(Math.random())
@@ -117,8 +117,8 @@ function NotesPage() {
117117

118118
/**
119119
* Изменение цвета карточки
120-
* @param {*} index
121-
* @param {*} color
120+
* @param {string} id
121+
* @param {string} color
122122
*/
123123
function changeNoteColor(id, color) {
124124
const index = getNoteIndexById(id)
@@ -129,9 +129,9 @@ function NotesPage() {
129129

130130
/**
131131
* Изменение текстового содержания карточки
132-
* @param {*} index
133-
* @param {*} name
134-
* @param {*} text
132+
* @param {string} id
133+
* @param {string} name
134+
* @param {string} text
135135
*/
136136
function editNoteContent(id, name, text) {
137137
const index = getNoteIndexById(id)
@@ -147,7 +147,7 @@ function NotesPage() {
147147

148148
/**
149149
* Изменение порядка заметки
150-
* @param {number} index
150+
* @param {string} id
151151
* @param {boolean} orderOperationFlag
152152
*/
153153
function editNoteOrder(id, orderOperationFlag) {
@@ -164,7 +164,10 @@ function NotesPage() {
164164

165165
///////////
166166

167-
/**функция получения карточки по id */
167+
/**
168+
* функция получения карточки по id
169+
* @param {string} id
170+
*/
168171
function getNoteById(id) {
169172
const byId = () => {
170173
let note = null
@@ -178,7 +181,10 @@ function NotesPage() {
178181
return id !== null ? byId() : null
179182
}
180183

181-
/**функция получения индекса карточки по id */
184+
/**
185+
* функция получения индекса карточки по id
186+
* @param {string} id
187+
*/
182188
function getNoteIndexById(id) {
183189
const byId = () => {
184190
let index = null

server/socket/wss.js

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,45 +3,64 @@ const WebSocket = require('ws')
33

44
/**
55
* Подключение WebSocket сервера
6+
* Он принимает сигналы об обновлении от клиента и рассылает остальным для синхронизации
67
* @param {*} port
78
*/
89
function startWSS(port) {
9-
let wsCount = 0
10+
/**сервер ws */
1011
const wsServer = new WebSocket.Server({ port })
12+
/**коллекция ws клиентов разделенная по id пользователя */
1113
const wsCollection = {}
14+
// обработка событий сервера
1215
wsServer.on('connection', (wsClient) => {
13-
wsClient.num = ++wsCount
14-
16+
// уникальный номер клиента
17+
const clientNum = Date.now()
18+
// проверка регистрации
19+
setTimeout(() => {
20+
if (!wsClient.userId) wsClient.close()
21+
}, 60 * 1000)
22+
// обработка сообщения клиента
1523
wsClient.on("message", (data) => {
1624
try {
17-
const { userId, target } = tryParce(data)
18-
25+
// данные с клиента
26+
const { userId, target } = JSON.parse(data)
27+
// обработка сообщения регистрации
1928
if (target == "register") {
2029
wsClient.userId = userId
21-
let clients = getClients(userId)
22-
clients.push({
23-
num: wsClient.num,
24-
send: msg => wsClient.send(msg)
30+
wsClient.num = clientNum
31+
let clients = getClients(wsClient.userId)
32+
let match = false
33+
clients.forEach(val => {
34+
if (val.num == wsClient.num) match = true
2535
})
26-
wsCollection[userId] = clients
36+
if (!match && wsClient.userId) {
37+
clients.push({
38+
num: wsClient.num,
39+
send: msg => wsClient.send(msg)
40+
})
41+
wsCollection[wsClient.userId] = clients
42+
} else throw new Error("ошибка регистрации сокета")
2743
}
28-
29-
if (target == "update") {
44+
// обработка сообщения об обновлении
45+
if (target == "update" && wsClient.userId) {
3046
getClients(wsClient.userId).forEach((wsc) => {
31-
if ((wsClient.num === undefined) || (wsClient.num !== wsc.num)) {
47+
if ((wsClient.num !== undefined) && (wsClient.num !== wsc.num)) {
3248
wsc.send(data)
3349
}
3450
})
3551
}
36-
37-
} catch (e) { }
52+
} catch (e) { wsClient.close() }
3853
})
39-
54+
// обработка закрытия клиента
4055
wsClient.on("close", () => {
41-
wsCollection[wsClient.userId] = getClients(wsClient.userId).filter((wsc) => {
56+
if (wsClient.userId) wsCollection[wsClient.userId] = getClients(wsClient.userId).filter((wsc) => {
4257
return (wsClient.num === undefined) || (wsClient.num !== wsc.num)
4358
})
4459
})
60+
// обработка ошибки клиента
61+
wsClient.on("error", () => {
62+
wsClient.close()
63+
})
4564
})
4665
wsServer.on("close", () => console.log("WSS closed"))
4766
wsServer.on("error", () => console.log("WSS error"))
@@ -55,11 +74,6 @@ function startWSS(port) {
5574
function getClients(userId) {
5675
return wsCollection[userId] || []
5776
}
58-
59-
function tryParce(str) {
60-
try { return JSON.parse(str) }
61-
catch (e) { return str }
62-
}
6377
}
6478

6579
module.exports = startWSS

0 commit comments

Comments
 (0)