-
Notifications
You must be signed in to change notification settings - Fork 0
/
\
83 lines (66 loc) · 1.94 KB
/
\
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
import {SET_AUTH_DATA, setWsActionCreator} from '../reducers/authReducer.js';
import {WS_MESSAGE} from '../reducers/messagesReducer.js';
const ws = store => next => action => {
console.log(SET_AUTH_DATA);
let result = next(action);
let state = store.getState();
const startWebSocketConnection = () => {
let ws = new WebSocket('ws://127.0.0.1:8181');
ws.onopen = (e) => {
store.dispatch(setWsActionCreator(ws));
ws.send(JSON.stringify({
token: state.auth.token,
id: state.auth.id,
action: 'AUTH',
}));
};
ws.onmessage = (event) => {
console.log(event);
//alert(`[message] Данные получены с сервера: ${event.data}`);
};
ws.onclose = (event) => {
if (event.wasClean) {
alert(`[close] Соединение закрыто чисто, код=${event.code} причина=${event.reason}`);
} else {
// например, сервер убил процесс или сеть недоступна
// обычно в этом случае event.code 1006
//alert('[close] Соединение прервано');
setTimeout(startWebSocketConnection(), 2000);
}
};
};
switch(action.type) {
case SET_AUTH_DATA:
startWebSocketConnection();
break;
case WS_MESSAGE:
let data = JSON.stringify({
id: state.auth.id,
action: 'SEND-MESSAGE',
user_id: action.user_id,
});
state.auth.ws.send(data);
break;
}
return result;
}
export default ws;
/*
const SET_WS = 'SET-WS';
const initial_state = {
ws: null,
}
const webSocket = (state = initial_state, action) => {
switch(action.type) {
case SET_WS:
return {
...state,
2оооол
let startWebSocketConnection = () => {
};
ws.onerror = (error) => {
//alert(`[error] ${error.message}`);
};
};
startWebSocketConnection();
*/