-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs-client.js
37 lines (30 loc) · 913 Bytes
/
js-client.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
const WebSocket = require('ws');
// Use URL parameters for authentication
const token = 'your_token_here';
const clientID = 'js-client-001'; // 设置客户端ID
const ws = new WebSocket(`ws://localhost:7502/?token=${encodeURIComponent(token)}&clientID=${encodeURIComponent(clientID)}`);
ws.on('open', function open() {
console.log('Connected to the server');
sendMessage();
});
ws.on('message', function incoming(data) {
console.log('Received:', data.toString());
});
ws.on('close', function close() {
console.log('Disconnected from the server');
});
ws.on('error', function error(err) {
console.error('WebSocket error: ', err);
});
function sendMessage() {
const message = {
from: 'js-client',
to: 'server',
subject: 'Hello',
content: 'How are you?',
type: 'msg'
};
ws.send(JSON.stringify(message));
}
// Send a message every 5 seconds
setInterval(sendMessage, 5000);