ghedipunk / PHP-Websockets

A Websockets server written in PHP.
BSD 3-Clause "New" or "Revised" License
913 stars 376 forks source link

How to ping a client #9

Closed Deele closed 10 years ago

Deele commented 10 years ago

I see that there is some parts of code, that deals with pinging. I want to disconnect and remove from active clients list a client, that has not sent a message or ping request for more than 30 seconds, but I don't see, how to achieve that. In addition to that, how to determine lag or ping time between server and client?

ghedipunk commented 10 years ago

The Ping and Pong control frames defined in the Websockets protocol is not recommended right now.

W3C has decided against putting any ping or pong APIs into the core Websockets API in the Javascript language. Discussion: https://www.w3.org/Bugs/Public/show_bug.cgi?id=13104

While some browsers may go ahead and add in an Pong mechanism to their Websockets implementation, this is non-standard, and does not happen in all modern browsers. Because of this, you can not and should not rely on the Ping and Pong control frames to see if a client is still responding.

Instead, I would suggest implementing it in your application unless and until the W3C decides to add ping and pong APIs to Javascript AND all major modern browsers start supporting it. I'm sorry that I don't have any more specific advice, but it would be difficult to give advice without knowing far too many details of your application's implementation.

Deele commented 10 years ago

My application is currently nothing more than your example. I'm testing different classes that people are already made, so I can use them in my project. If you can, please, give me advice in generic environment or in abstract code, how ping/pong and latency could be implemented.

ghedipunk commented 10 years ago

I would have the application send formatted data back and forth, such as in JSON or, if I'm feeling masochistic, in XML. This way, I can specify what type of information is being sent.

For instance, if I were to send a chat message, I would send:

type = chat from = username timestamp = 12345678 content = This is a message

In the case of a ping message, I would send:

type = ping nonce = a1b2c3d4e5f6

When sending the ping, I would store the nonce, the client's connection handle, and a timestamp (see: PHP's microtime() ), probably in a global array. When the client responds with the pong, I will look up the nonce, then compare the client's connection handle to make certain that nobody is spoofing connections. If the pong is correct, I would compare the time sent with the time received to get the RTT.

The client-side Javascript should simply echo the nonce back, sending:

type = pong nonce = a1b2c3d4e5f6

Note: I strongly suggest JSON rather than key/value pairs separated by newlines like my examples show, as JSON encoding and decoding has built in escaping.