-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-websocket.js
More file actions
64 lines (54 loc) · 1.63 KB
/
test-websocket.js
File metadata and controls
64 lines (54 loc) · 1.63 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
import { WebSocket } from 'ws';
// Create a WebSocket connection to our server
const url = 'ws://localhost:5000/ws';
console.log(`Connecting to WebSocket at ${url}...`);
const ws = new WebSocket(url);
ws.on('open', () => {
console.log('Connection established!');
// Send an identification message
const identifyMsg = { type: 'IDENTIFY', userId: 1 };
console.log('Sending identity message:', identifyMsg);
ws.send(JSON.stringify(identifyMsg));
// Send a test message after a delay
setTimeout(() => {
const testMsg = {
type: 'NEW_MESSAGE',
payload: {
matchId: 1,
senderId: 1,
receiverId: 2,
content: 'Test message from WebSocket script',
createdAt: new Date(),
read: false
}
};
console.log('Sending test message:', testMsg);
ws.send(JSON.stringify(testMsg));
// Close the connection after sending the message
setTimeout(() => {
console.log('Test complete. Closing connection.');
ws.close();
process.exit(0);
}, 1000);
}, 1000);
});
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
console.log('Received message:', message);
} catch (err) {
console.error('Error parsing message:', err);
console.log('Raw message:', data.toString());
}
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
ws.on('close', (code, reason) => {
console.log(`Connection closed. Code: ${code}, Reason: ${reason || 'No reason provided'}`);
});
// Exit after 10 seconds if still running
setTimeout(() => {
console.log('Timeout reached. Exiting...');
process.exit(1);
}, 10000);