forked from trinhdvt/lang-thang
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
93 lines (82 loc) · 2.76 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello WebSocket</title>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
<button id="connect-btn" onclick="connect()">Connect Socket</button>
<button id="login-btn" onclick="login()">Login</button>
<button id="subscribe-notify-btn" onclick="subscribe_notify()">Subscribe Notify</button>
<button id="subscribe-post-btn" onclick="subscribe_post()">Subscribe Post</button>
<button id="disconnect" onclick="disconnect()">Disconnect</button>
<script type="text/javascript">
let ws = null;
let email = 'trinhvideo123@gmail.com';
let password = 'trinhvideo123';
let token = null;
let notificationSubscription = null;
// có thể gọi lúc bắt đầu load trang
// kết nối đến socket server
function connect() {
const socket = new SockJS("http://localhost:8080/socket-server");
ws = Stomp.over(socket);
ws.connect({}, function (frame) {
console.log(frame);
}, function (error) {
console.log(error);
});
}
// đăng nhập để lấy token
function login() {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/auth/login',
data: {
'email': email,
'password': password
},
dataType: 'json',
}).done(function (data) {
token = data['token'];
console.log(data);
}).fail(function (error) {
console.log(error);
})
}
// subcribe để nhận thông báo mới nhất
function subscribe_notify() {
if (ws != null) {
notificationSubscription = ws.subscribe(`/topic/notify/${email}`, function (notify) {
// notify.body chính là thông báo mới nhất
console.log(notify.body);
}, {'Authorization': `Bearer ${token}`});
}
}
// unsubsribe sau khi logout
function unsubscribe_notify() {
if (notificationSubscription != null) {
notificationSubscription.unsubscribe();
}
}
// đăng ký nhận comment mới nhất
function subscribe_post() {
if (ws != null) {
ws.subscribe("/topic/post/1", function (comment) {
// comment.body chính là comment mới nhất
console.log(comment.body);
})
}
}
// có thể gọi cái này lúc thoát trang
// disconnect thì có nghĩa là sẽ unsubcribe toàn bộ
function disconnect() {
if (ws != null) {
ws.disconnect();
}
}
</script>
</body>
</html>