12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import { SearchService } from "../services/query.service"
- import _ = require("lodash")
- import { Subject, interval } from "rxjs";
- import { io } from "socket.io-client";
- import { Server } from "socket.io"
- import { UtilityService } from "../services/utility.service";
- const util = new UtilityService()
- util.checkMaxHeap()
- /* ---------------------- COMPLEX OPERATION ------------------------------ */
- // Create new Subject to handle incoming data from remote subscription
- let payload: Subject<any> = new Subject()
- payload.subscribe((element) => {
- // console.log(`Received message from server: ${element.appData.msgId}`);
- })
- // Create new Subject to monitor and broadcast heap size
- let trafficControl: Subject<any> = new Subject()
- let intervalChecking = interval(5000)
- intervalChecking.subscribe(() => {
- trafficControl.next(util.checkHeapSize())
- })
- // Create a WebSocket server
- function createWebsocketServer() {
- const io = new Server({})
- // Listen for connections to the WebSocket server
- io.on(`connection`, (socket) => {
- console.log(`Connected to clients`);
- // Subscribe to the subject when a client connects
- const subscription = trafficControl.subscribe((element) => {
- socket.emit('trafficControl', element);
- });
- socket.on(`disconnect`, () => {
- console.log(`Clients Disconnected`)
- subscription.unsubscribe()
- })
- })
- // create localhost server port 8080
- io.listen(8081);
- }
- // Create a new WebSocket client
- function connectWebSocket() {
- const socket = io('http://localhost:8080')
- // Listen for the WebSocket connection to open
- socket.on(`connect`, () => {
- console.log(`Connected to publisher'server`)
- // Listen for messages from the server
- socket.on('message', (message) => {
- trafficControl.next(message);
- });
- })
- // Receive payload from publisher and push them into local Subject
- socket.on('payload', (data: any[]) => {
- console.log(data.length)
- data.forEach(element => {
- payload.next(element)
- });
- })
- // Listen for the disconnect event
- socket.on('disconnect', () => {
- console.log(`Disconnected from publisher'server`);
- // Attempt to reconnect every 3 seconds
- setTimeout(() => {
- console.log('Attempting to reconnect...');
- socket.connect();
- }, 1000);
- });
- // Listen for errors
- socket.on('error', (error) => {
- console.error('Socket error:', error);
- });
- }
- createWebsocketServer()
- connectWebSocket();
|