Customizing the standard ping protocol for native JavaScript websockets

In my Expo (React Native) project, I am working on implementing a protocol to manage stale websocket connections on both the client and server sides. The 'ws' package offers built-in callback handling for the 'pong' event (and sending pings), making server-side management in NodeJS relatively straightforward.

However, I'm encountering difficulties with the client side. The native WebSocket object does not provide a callback function for responding to pings from the server. Although it does respond correctly to server pings with opcode 0x9, these messages are not captured by the WebSocket.onmessage handler.

Below is my current attempt at a client-side ping handler:

const heartbeat = () => {
            console.log("heartbeat");

            clearTimeout(pingTimeout!);

            pingTimeout = setTimeout(() => {
                socket.close();
                setResetConnection(rc => !rc);
            }, HEARTBEAT_INTERVAL + HEARTBEAT_LATENCY);
};

socket.onmessage = (event) => {
            console.log("message");

            if (event.data instanceof Blob) {
                console.log("received ping");
                heartbeat();
                const response = new ArrayBuffer(1);
                const view = new Uint8Array(response);
                view[0] = 0x9;
                socket.send(view);
                return;
            }

            [...remaining onmessage code...]
}

The socket is initialized as

var socket = new WebSocket("ws://ipaddr:8080");

As noted, the pong is sent back to the server automatically without giving the client any opportunity for additional logic. I am currently looking for a way to override this default behavior without having to create my own ping/pong protocol.

Answer №1

@dandavis gave the right answer; it's absolutely fine to use socket.onclose()

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

What is the method for setting the content-type in an AJAX request for Android browsers?

I am facing an issue with my ajax call to the Rails server. The response from the server varies between HTML and JSON based on the content type. Surprisingly, this works smoothly on iPhone and desktop browsers like Chrome, but I am encountering a problem o ...

Is there a way for me to automatically update my URL with different API IDs as I iterate through a JSON array?

While iterating through my JSON file, I use a forEach loop to extract all the IDs like this: var gameId = request("https://api.sportradar.us/ncaamb-t3/games/" + yyyy + "/" + mm + "/" + dd + "/schedule.json?api_key=************", function(error, response, ...

A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON fi ...

Leverage Hubspot and Google Analytics to transfer session source and medium data

Is there a way to track session source and medium information in HubSpot to identify where a specific visit originated from before a form is filled out or another conversion event occurs? Ideally, this process would involve transferring the session and me ...

Avoid selecting primary key column in TypeORM查询

Is it possible to exclude primary key columns from being selected in TypeORM? I've tried using the select false option, but it doesn't seem to work for these specific columns. Could it be because they are essential for identifying the entity or b ...

Ways to implement a transition effect when the hover state is deactivated or no longer present

After applying a transition to the header using the hover pseudo-class, I noticed that it abruptly snaps back to its original position when the hover effect is removed. Is there a way to smoothly return the header to its original position using the same ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section. <Collapse defaultActiveKey={["1"]} expandIconPosition="right" > <Panel header="This is p ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...

Utilizing JSON information acquired through AJAX within a distinct function

Sorry if this question has been asked before, I tried following suggestions from another post but they didn't work for me. What I'm trying to do is fetch some JSON data, save a part of it in a variable, and then use that variable in a different f ...

Formula for determining the slider's span

I recently created a range slider using Vue.js It has a minimum and maximum value, assumed to be percentages as it ranges from 0 to 100. My goal is to set the minimum value at $5,000 and the maximum at $200,000, However, I struggle with math and need th ...

Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows: By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg. This will result in the stub executing the first callback it ...

Scrolling to the top of the Popper component when an element is selected

I am currently utilizing the Autocomplete Material UI control with multiple selections enabled. Here is the code snippet I have created based on this answer: <Autocomplete PopperComponent={PopperMy} ... /> const PopperMy = function (props) ...

Having difficulty iterating through a JSON object in NodeJS

My NODEJS program utilizes xml2js to convert an XML file into JSON and parse it. However, when attempting to loop through the JSON object to display the ID and LastReportTime for each entry, I receive an output stating 'undefined'. Output 2015- ...

How to Use Google Calendar API to Retrieve Available Time Slots for a Given Day

Is there a way to extract the list of available time slots from my Google Calendar? Currently, I am only able to retrieve the list of scheduled events. I am utilizing the Google Calendar npm package. google_calendar.events.list(calObj.name,{ timeMin ...

How to delete rows from a table in bootstrap with JavaScript

My goal is to create a table that allows users to delete specific rows using JavaScript and bootstrap. I attempted the standard method, but it doesn't seem to be working: <form action="scrivi.php" method="POST"> <t ...

Retrieve attributes of an html element modified by AJAX request

I am currently developing a small project that involves performing CRUD operations on a MySQL table using PHP and jQuery. The table is integrated into the layout in the following manner: <?php require '../connect.php'; $sql = "SELECT id ...

"Effortlessly move elements with HTML5 drag and drop functionality from either direction

I'm working on an application that requires Html5 Drag and Drop functionality, which is currently functioning well. However, in the app, there may be instances where a dropped item is no longer needed and I want to allow users to re-drag and drop it b ...