-
Notifications
You must be signed in to change notification settings - Fork 0
/
index5 - Copy.js
78 lines (57 loc) · 2.17 KB
/
index5 - Copy.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
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
const WebSocket = require('ws');
const express = require('express');
const port = 3000;
let counter = 0; // Initialize the loop counter
let clientId = null;
// Create the App Express Server
const app = express();
// Create a WebSocket client that connects to the server on port 8080
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => {
console.log('Connected to WebSocket server');
// Send a message to the server
const message = JSON.stringify({ type: 'client-id', id: clientId, message: 'The Express Client has connected!'});
ws.send(message);
});
ws.on('message', (message) => {
const data = JSON.parse(message); // Assuming JSON messages
console.log(`Json Received from Server: ${JSON.stringify(data, null, 2)}`);
if (data.type === 'client-id') {
console.log(`Received data.type: [${data.type}]`);
console.log(`Received data.id: [${data.id}]`);
console.log(`Received data.message: [${data.message}]`);
// Store the client ID for future use
if (clientId === null)
clientId = data.id;
}
if (data.type === 'client-express') {
console.log(`Received data.type: [${data.type}]`);
console.log(`Received data.id: [${data.id}]`);
console.log(`Received data.message: [${data.message}]`);
}
if (data.type === 'client-dotnet') {
console.log(`Received data.type: [${data.type}]`);
console.log(`Received data.id: [${data.id}]`);
console.log(`Received data.message: [${data.message}]`);
}
else {
console.log(`Received message from server: ${message}`);
}
});
ws.on('close', () => {
console.log('Connection closed');
});
ws.on('error', (err) => {
console.error(`WebSocket error: ${err}`);
});
app.get('/trigger', (req, res) => {
counter++;
const jsonData = JSON.stringify({ type: 'client-express', id: clientId, message: 'The [trigger] endpoint was encountered (' + counter + ')' });
console.log(`Sending message [${jsonData}] from the Express App`);
// Send a message to the TCP server when this endpoint is triggered
ws.send(jsonData);
res.send('Message sent to TCP server.');
});
app.listen(port, () => {
console.log(`HTTP server listening on port ${port}`);
});