Javascript - WebSocket client encountering issues with onmessage event not triggering upon receiving a large response from the server

My task involves creating a .NET WebSocket server using TcpClient and NetworkStream to communicate with a JavaScript client. The client initiates the connection and requests specific actions from the server, which then generates responses. Previously, these responses were short JSON strings sent back to the client successfully.

However, when the requirement arose to send larger string responses, such as base64 encoded images exceeding 200k bytes, the client stopped receiving responses and the onmessage event was not triggered. Sending shorter JSON data worked fine, indicating an issue specifically with larger data.

Here is an example of sending large data:

https://i.sstatic.net/MIWQs.png

And here is an example of sending simple data:

https://i.sstatic.net/D0fIt.png

On the client side, I have stripped down the code to remove any unrelated components, but the behavior remained consistent:

try{
    ws = new WebSocket("ws://127.0.0.1:8282");
    ws.binaryType = "arraybuffer";
}
catch(err){
    debugger;
    document.getElementById("message").innerHTML = "Not Connected! " + err;         
};
ws.onopen = function () {
    var jsonRequest = '{"action" : "START_STREAM","timeout"  : 20}';
    ws.send("START_STREAM");
};

As for the server-side code, after generating the response (which includes a plain string with base64 encoded image), the following method is executed:

 Byte[] frame = CreateFrameFromString(serverResponse);
 networkStream.Write(frame, 0, frame.Count());
 networkStream.Flush();
 clientSocket.Close();
 clientSocket = ServerListener.AcceptTcpClient();
 networkStream = clientSocket.GetStream();

The initialization code for the server thread is as follows:

 ServerListener.Start();
 clientSocket = ServerListener.AcceptTcpClient();
 NetworkStream networkStream = clientSocket.GetStream();
 while (true)
    {
     if (!networkStream.DataAvailable)
  ...regular loop/server stuff/handshake etc.

Below is the method 'CreateFrameFromString' that handles framing the message before sending it:

 private static byte[] CreateFrameFromString(string message, Opcode opcode = Opcode.Text)
    {
        var payload = Encoding.UTF8.GetBytes(message);

        // Frame creation logic...

        return frame;
    }

Upon testing, I found that I could successfully send responses with up to 4250 characters without any modifications to the setup. However, once I exceeded that limit, the responses started disappearing. Are there any protocol or buffer size considerations that I might be missing?

Answer №1

Following extensive troubleshooting, I discovered the solution was to transmit data in smaller packages rather than as a single unit. By dividing the response into chunks of 50,000 characters and sending them individually, I was able to piece together the complete message on the client side using the onmessage event. Once all response segments were transmitted, the session was closed, prompting the creation of an image from the base64 stream on the client side.

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

Trying to modify the chosen option while filtering an ajax source using select2?

I am currently integrating the select2 library within a Bootstrap 4 modal in the following manner: <div class="form-group" id="fg-jbInd"> <label for="jbIndustry" class="control-label"gt;Industry * <sele ...

Implement models in NodeJS that can handle versioning and variations

Utilizing NodeJS on my server, I have various server-side business models such as products, customers, widgets, and documents that can all be stored in the database. I am interested in adding the following features to some of these models: versionable va ...

Transferring data using AJAX between an AngularJS frontend and a Node.js backend

Just a heads up: The main question is at the bottom in case you find this post too lengthy ;) I'm currently working on developing my first angularjs app and I've hit a roadblock when it comes to fetching data via ajax from my nodejs (express) se ...

The Star Rating System fails to update accurately after hiding the Radio Buttons

I followed a tutorial to set up a Star Rating System Everything was working fine on the SHOW PAGE and the INDEX PAGE until I decided to hide the Radio Buttons and use the corresponding labels to submit the value. I encountered an issue where the JavaScrip ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Nock is capturing my request, however, my AJAX call is encountering an error

I am currently conducting a test on an AJAX request using the XMLHttpRequest method: export default function performTestRequest() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/service'); xhr.onload = ( ...

tips for integrating new features in protractor

Currently in our testing process we utilize protractor/selenium for test automation. I am eager to enhance certain functions, such as sendkeys and click, to not only log actions to the console but also increase reliability (we have observed that click fail ...

.push issue encountered in older browsers IE6 and Safari

There is a click event that works perfectly in Firefox and IE 9 where the goal is to select an item from a dropdown, push the value into an array, display it in a div, and then parse the list in PHP on "submitList" click. If the value is empty, both the ar ...

Issue encountered: Failure in automating login through Cypress UI with Keycloak

Struggling with automating an e-commerce store front using Cypress, specifically encountering issues with the login functionality. The authentication and identity tool in use is keycloak. However, the Cypress test fails to successfully log in or register ...

Prevent unnecessary re-renders of components by optimizing state changes with hooks

In my Layout component, there is a Table component with an Entry component for each row. Each row can be selected, and when a row is selected, it is added to the state so that all selected entries can be sent to a REST service later using a button. The i ...

dropdown menu with list of identifiers

I am looking to dynamically generate IDs for my combobox and checkbox based on an array. For example, I want IDs like "mySelect1", "mySelect2" or "checkid1", "checkid2". Could you please assist me with this? Below is the code I have so far: <script typ ...

Hiding both clear buttons in the MUI Autocomplete component on Chromium: A simple guide

The issue with the clear button is specific to Chromium; it does not appear in Firefox. Take a look at an example of a MUI React Autocomplete component displaying two clear buttons. Various solutions mentioned in this thread only hide the rightmost butto ...

Arrange elements prior to the treeview within the unordered list/ list items

Below is a snippet of code that I am working with: <ul> <li>group 1 <ul> <li>group 1.1</li> <li> group 1.2</li> <li>group 1.3 <ul> <li>group 1.3.1</li> <l ...

How to create a manual mock for @material-ui withStyles in React using Jest

I have been experimenting with creating manual mocks for the @material-ui/core/styles module, specifically targeting the HOC known as withStyles. Initially, using an inline mock with jest.mock function worked flawlessly. However, when attempting to reloca ...

What is the best way to modify the state of a nested component?

I am facing a challenge in my React project where I have two buttons in my App.js. When either of the buttons is clicked, I want to change the current state (list) to display in descending order based on the button pressed (order by date or order by upvo ...

Challenges with JavaScript setInterval

Hello everyone! I'm currently working on running a loop with setInterval, but I want each element in the array to use a random interval instead of the entire array doing so. Below is the code I have been using: setInterval(function() { for ( ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Render the React component asynchronously, only after the data has been successfully fetched

I am looking to display a component only after the necessary data has been fetched. If I try to load the data instantly, the component gets rendered but no information is displayed. class App extends React.Component { //typical construct fetchGameD ...

Controlling the activation of a button on a parent modal popup from a child within an IFrame using javascript

I am struggling to toggle the button on the main window from the child window. Here is a snippet from the main page: <ajaxToolkit:ModalPopupExtender ID="mpeTest" runat="server" CancelControlID="btnClose" PopupControlID="pnl1" TargetControlID="showMp ...