NestJS Socket.IO seemingly struggles to establish and maintain a stable connection: constantly disconnecting and then reconnecting

I'm currently attempting to integrate Socket.IO with NestJS. Upon loading the front end, I am noticing a high frequency of connections and disconnections to the NestJS gateway.

Below is an example of the connection/disconnection logs:

[Nest] 12232   - 01/06/2021, 11:28:24 AM   [NotificationGateway] Client connected: a2f47PSPB9oUn74AACr
[Nest] 12232   - 01/06/2021, 11:28:30 AM   [NotificationGateway] Client connected: NPBzcFBJLHAkQmcAACs
[Nest] 12232   - 01/06/2021, 11:28:30 AM   [NotificationGateway] Client disconnected: hM8j9f9Fd6zT2HJiAACn
[Nest] 12232   - 01/06/2021, 11:28:36 AM   [NotificationGateway] Client disconnected: kx6x1FMIPqfPNZa9AACo
[Nest] 12232   - 01/06/2021, 11:28:36 AM   [NotificationGateway] Client connected: hHWW5iusE86GaszSAACt
[Nest] 12232   - 01/06/2021, 11:28:42 AM   [NotificationGateway] Client connected: V3ah407F2uCge4GxAACu
[Nest] 12232   - 01/06/2021, 11:28:42 AM   [NotificationGateway] Client disconnected: c-VEB3fnPCWGt8hlAACp
[Nest] 12232   - 01/06/2021, 11:28:48 AM   [NotificationGateway] Client connected: NGuWrdwUQiKigGspAACv

The "Connected" console.log statement never seems to execute.

Here is a snippet of my simple client-side code :

<!doctype html>
<html>
    <head>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js'></script>
        <script>
            const socket = io.connect('http://127.0.0.1:3000/');
            socket.on('connected', function() {
                console.log("connected !");
            });
            socket.connect();
        </script>
    </head>
    <body>
    </body>
</html>

And here is a segment from my NestJS gateway logic:

interface SockClient {
  uid: string;
  sock: Socket;
}

// @Injectable()
@WebSocketGateway()
export class NotificationGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  constructor(
    @Inject(forwardRef(() => NotificationService))
    private readonly notificationService: NotificationService,
    @Inject(forwardRef(() => HttpService))
    private readonly httpService: HttpService,
  ) {}

  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('NotificationGateway');

  private clients: SockClient[] = [];

  // Additional methods...

You can view a screenshot of my Chrome requests tab here.

Despite following various tutorials meticulously, I have been unable to pinpoint the root cause of the issue. Any assistance would be greatly appreciated. Thank you!

Answer №1

It appears that you are currently utilizing Socket.IO version 3, which is not yet compatible with Nest. Consider reverting back to version 2.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it better to subscribe or utilize backing properties to update dependent data within a component?

I struggle with determining the most effective practices for Angular. The issue I am facing is as follows: <div> <app-child [data]="data | async"> </app-child> </div> Should I opt for the following option: A: Uti ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

No members were exported by the module, please export an interface

I encountered this error: "/Users/robot/code/slg-fe/src/app/leaderboards/leaderboards.component.ts (2,10): Module '"/Users/robot/code/slg-fe/src/app/leaderboards/leaderboard"' has no exported member 'Leaderboard'. This is what my le ...

What is the best way to rekindle the d3 force simulation within React's StrictMode?

Creating an interactive force directed graph in React using D3 has been successful except for the dragging functionality not working in React StrictMode. The issue seems to be related to mounting and remounting components in ReactStrict mode 18, but pinpoi ...

Encountering a node module issue when implementing graphql in a TypeScript project

I encountered issues when attempting to utilize the @types/graphql package alongside TypeScript Node Starter node_modules//subscription/subscribe.d.ts(17,4): error TS2314: Generic type AsyncIterator<T, E>' requires 2 type argument(s). node_modu ...

Tips for changing a created Word file with Docxtemplater into a PDF format

Hey there! I am currently in the process of building a website with Angular.js and have successfully managed to generate a word document from user input. Everything was working fine until I encountered an issue. I now need to provide a way for users to pr ...

With a single click, Clickaway is triggered not once, but twice

I am working on creating a filter component where I can pass filter options down to my child component. Each filter has a click event to open the filter for user selection, as well as a v-on-clickaway event that closes the options when the user clicks away ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this: const usersURL = 'http://my.super.url.php'; @Injectable() export class UserService { users: Observable<User[]> constructor (public http:Http) let tick$ = Observ ...

Scanning sockets with Android's AsyncTask

I need advice on how to efficiently loop through a range of IP addresses (e.g., 192.168.5.0-192.168.5.255) to identify devices that are listening on a specific port. Although the current code is functional, I am concerned that it may not detect all devices ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

Obtain the total number of requests submitted by the user within a 24-hour period

I have a POST request point in my API where I need to track and store all work journals made by a worker. export const registerPoint = async (req: Request, res: Response) => { const user = res.locals.decoded; const {id} = user; const point = new Point ...

Automatically Parse Value by 100 in Angular FormGroup

Within my Angular form group, I have 3 fields. One of these fields serves as a tool for the user, automatically calculating the value based on another field. Essentially, when a user inputs a number, the tool field displays that value divided by 100. Here ...

A guide to using the up and down keys to switch focus between div elements in a react component with TypeScript and CSS

I am currently working with a scenario where data is being displayed within different div elements, and I wish to enable the selection/focus of a specific div when users use the up/down arrow keys. While trying to achieve this functionality by using refs ...

What is the reason behind TypeScript's restriction on referring to const variables in type definitions?

Defining a type that restricts the input string to two possible values can be done like this: type STATE_TYPE = 'DRAFT'|'PUBLISHED' function myFunc(state: STATE_TYPE) { ... } However, when trying to define the two values as const and ...

Is it possible to combine two enums in TypeScript to create a single object with key-value pairs?

Incorporating two enums named Key and Label, as well as an interface called IOption, the goal is to generate an array of objects known as IOptions. const enum Key { Flag = 'flag', Checkbox = 'checkbox', Star = 'star&apo ...

What is the process for utilizing a variable as a string or object in TypeScript?

Consider the scenario where a variable may hold either a string or an object with properties like this: value?: string | { name: string, type: string } Attempting to work with it below leads to a compile error: console.log(value?.name || value) console.lo ...

PHP error: Unable to locate class (Possibly due to Composer failing to install all classes?)

Currently facing a dilemma with implementing phpsocket.io. The installation instructions are confusing, leaving me stuck at a frustrating roadblock. Despite using Getcomposer.org to install the package, not all necessary classes were included. Attempting t ...

Can you explain the distinction between ()=>any and {():any} in Typescript?

There is no issue with this code now, and the Typescript compiler deems it completely valid. However, are these two type definitions truly identical? Can someone provide an explanation of the differences between them, along with some practical examples f ...

An error message stating 'Cannot read the name property of undefined' is being displayed, despite it being expected to be defined

interface InputField { readonly label : string; readonly data : string; readonly displayInline ?: boolean; } class FormField implements InputField { readonly label : string; readonly data : string; readonly displayInline ?: boolean; constru ...