-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.js
39 lines (31 loc) · 1.25 KB
/
ws.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
const { PubSub } = require('@google-cloud/pubsub');
const WebSocket = require('ws');
// Creates a PubSub client
const pubSubClient = new PubSub();
// References an existing subscription, or creates a new one
const subscriptionName = 'ethereum_token_transfers_usdt'; // Choose your subscription name
const subscription = pubSubClient.subscription(subscriptionName);
const wss = new WebSocket.Server({ port: 1234 });
// Listen for new WebSocket connections
wss.on('connection', ws => {
console.log('Client connected');
// Listen for new messages from Pub/Sub and send them to connected clients
subscription.on('message', messageHandler);
function messageHandler(message) {
console.log(`Received message: ${message.id}`);
console.log(`Data: ${message.data}`);
ws.send(message.data.toString());
message.ack();
}
// Handle any errors that occur during the WebSocket connection
ws.on('error', error => {
console.error(`WebSocket error: ${error.message}`);
});
// Handle WebSocket closure
ws.on('close', () => {
console.log('Client disconnected');
// Remove Pub/Sub listener when the client disconnects
subscription.removeListener('message', messageHandler);
});
});
console.log(`WebSocket server is running on port 1234`);