What are the available events offered by Express websockets?

I am interested in learning about the different websocket events available. Currently, I have only used the ws.on('message') event, but I would like to find out how to detect when the connection is established and closed. I attempted to add the ws.on('connection') event, but it did not work.

This is my code:

app.ws('/', function (ws, req) {
    ws.on('message', function (textChunk) {
            //do something
        }
    });
});

Do I need to implement some client-side programming for this functionality?

I also tried adding the following code, but it did not trigger when I connected from my client.

ws.on('request', function () {
  console.log("request");
});

Answer №1

The app.ws function is used to define the behavior when a new websocket connection is established. Here is an example of how you can use it:

app.ws('/', function (ws, req) {

    console.log("A new connection has been opened!");

    ws.on('close', function() {
        console.log('The connection was closed!');
    });

    ws.on('message', function (message) {
        console.log('Message received: '+message);
    });
});

Answer №2

Upon analyzing the source code of express-ws, it appears that the following actions can be performed.

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);

// retrieve the WebsocketServer instance with getWss()
expressWs.getWss().on('connection', function(ws) {
  console.log('connection open');
});

// ... express middleware

// ... websocket middle ware
app.ws('/', function(ws, req) {
  ws.on('message', function(msg) {
     console.log(msg);
  });
});

app.listen(3000);


New Response

The available options include:

close
error
message
open

Visit this link for more details on WebSocket attributes.

Answer №3

After some digging, I managed to discover another event that is actually triggered. If only I could come across one that is called just once upon opening the connection.

app.ws('/', function (ws, req) {

    ws.on('close', function() {
        console.log('connection closed');
    });

    ws.on('message', function (textChunk) {
            //adding functionality here
        }
    });
});

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

Invoke the prototype function through an onclick event after dynamically adding a button

Within my code, I have created two prototype functions named showPopup and buildView. The buildView function is responsible for generating dynamic HTML that includes a button. My intention is to invoke the showPopup function when this button is clicked. Ho ...

Vulnerability protection against AngularJS JSON is not removed

I am currently working on an Angular app that communicates with an API. The JSON responses from the API are prefixed with )]}', as recommended in Angular's official documentation. The issue I am facing is that my browser seems to try decoding th ...

Load suggestions from Material UI AutoComplete dynamically based on user input

I am facing a challenge with an Autocomplete component that needs to handle a large data list, up to 6000 elements, and display suggestions based on user input. Due to the sheer number of options, when a user types on a slower computer, there is a noticeab ...

Create the next app with updated files by rebuilding it while utilizing express as the server

I'm currently utilizing the combination of Next.js and Express.js in my project. In this setup, Express handles all the routing tasks instead of Next.js. For a smoother development experience, I require a process where whenever a file is modified, Ne ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

AngularJS - Organize Item Hierarchy with Separate Containers for Each Group

My goal is to incorporate a $scope variable within an AngularJS controller that has the following structure: $scope.hierarchy = { name: 'bob', selected: true, children: [ { name: 'frank' }, { name: 'spike' ...

Even after shutting down my PeerConnection, the black screen persists. I would appreciate assistance in resolving this issue

Welcome to the Room.js Client Side Code! import React, { useEffect, useRef, useState } from "react"; import io from "socket.io-client"; import Peer from "simple-peer"; import styled from "styled-components"; const C ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

Setting up redux with Next.js: a step-by-step guide

After setting up redux in this manner, everything is functioning properly. The _app.js file has been reorganized as follows : import App from 'next/app'; import { Provider } from 'react-redux'; import withRedux from 'next-redux-wr ...

What causes the circular progress bar to disappear when hovering over the MUI React table?

My goal was to create a table with a CircularProgressBar that changes its background color from orange to dark blue when hovering over the row. However, despite my efforts, I couldn't get it to work as intended. Additionally, I wanted the progressBar ...

Why isn't my React image updating its source right away? What are some solutions to this issue?

I currently have a basic <img> tag with a specified src attribute. <img src={src} /> When I update the src attribute from, let's say /1.jpg to /2.jpg, there is a delay in loading the new image. React still displays the old image (/1.jpg) ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

Transition your Sequelize migrations to TypeORM

I'm currently in the process of transitioning a Node.js application from vanilla JS to Nest.js. In our previous setup, we used Sequelize as our ORM, but now we've decided to switch to TypeORM for its improved type safety. While exploring the Type ...

Is it time to swap out "localhost" with the service name in Docker?

I have successfully dockerized my reactjs app and express app. Check out the docker-compose.yml file I used: version: "3" services: client: image: react-app build: ./client ports: - "3000:3000" volumes: ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

Can you help me identify the issue with my current Jade for loop implementation?

Here is my full loop code written in Jade: block content div(class='row') div(class='col-lg-12') h1(class='subject') 로또라이 div(class='row') div(class='col-lg-8') - for (var ...

Using Array.push on MongoDB does not appear to function as expected

My goal is to implement a dynamic vector/array feature in MongoDB where each submission made by a user will update the database accordingly. I have already created a variable for this purpose and tested it successfully with the correct user being found. H ...

Tips for effectively timing out a Node.js Oracle DB connection that fails to respond

I am currently utilizing Npm Oracle in my Node.js application. I am facing an issue where my compiler hangs while trying to connect to the Oracle database, causing a thread to get stuck. I need to implement a timeout mechanism as my client cannot wait for ...