Forum Moderators: open

Message Too Old, No Replies

WebSocket messages all at once

         

Nutter

1:25 am on Feb 8, 2021 (gmt 0)

10+ Year Member



I've got a PHP WebSocket server that sends multiple messages back to the client, with a delay between each message. To test it's sending a message, sleeping for a couple of seconds, sending another message; rinse repeat a few times. I can watch what the server is sending and it's sending out a message every 2 seconds like it should be.

My JS looks like this.
var ws = new WebSocket('ws://example.com:1234');
ws.addEventListener('message', function(msg) {
console.info(msg);
});


I assumed, and I guess could be wrong, that the message would show up in the console as they come in. But that's not what's happening. They're all showing up, but only after the last message is received. Then they all dump to the console at once.

Am I missing something, or is this how the message event works? If that's the way it works, is there a way around it so that the JS can act immediately when a message comes in instead of waiting until they're all in.

NickMNS

3:25 am on Feb 8, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The problem is not on the client side. WebSocket will log the messages as they come. It may be that your webserver, I assume Apache, is buffering the messages before sending them. What ever the reason in Google Chrome (Firefox too) you can go to the network tab in dev tools and click on the url, and it should show the stream of messages coming in and the timestamp. If you see the messages arriving in batches then you'll know it is a server side issue, if not then there is an issue with your client side implementation.

I have an app running that receives dozens of messages a second, and in order not to overwhelm the client I needed to implement buffering on the client side, my buffer is set at 100ms.

Nutter

3:56 pm on Feb 8, 2021 (gmt 0)

10+ Year Member



Thanks for pulling me out of that rabbit hole. Chrome developer is showing that all the messages are coming in a batch even though the server script is showing the messages going out at the right time.

Now I've got another rabbit hole to dig through :)

NickMNS

4:28 pm on Feb 8, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Are you using Apache? I use NginX, but my server side language is Python.

Nutter

11:54 pm on Feb 8, 2021 (gmt 0)

10+ Year Member



Apache, but the socket is running through PHP on the command line.

NickMNS

12:42 am on Feb 9, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I realize that you are using PHP but the http/ws requests are still being handled by the webserver, and it is the webserver that is causing the batching. There is certainly a setting that needs to be changed to allow the data to flow unimpeded.