Ikari
Ikari

Reputation: 3246

How to understand, for which route a websocket message was sent by the client in a server?

I was building a server, and while trying to implement the websocket protocol, I ran into some problem.

As the question title describes, let's suppose I have defined two routes (/ws1, /ws2), which exposes multiple websocket connection.

And in case of a handshake I successfully can understand for which route the handshake request was sent.

The main problem in hand is that, when a subsequent websocket message is sent by the client, how is the server going to understand that which endpoint the websocket message was sent to.

After reading this: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers I understand that there is no such field in message which denotes the route.

Just in case: I am doing this in PHP.

Upvotes: 4

Views: 830

Answers (2)

Sherif
Sherif

Reputation: 11943

The route never changes after the handshake is completed. The idea is that the WebSocket maintains a state-full connection, but that connection is first negotiated over HTTP. This is done by sending a normal HTTP request to a URI and the end-point is then responsible for maintaining the connection after it has been successfully negotiated.

As such it is your responsibility to keep track of the information in that initial HTTP request, after the WebSocket connection is negotiated, if you wish to make subsequent use of it.

If you look at how some current PHP implementations of WebSocket servers do it, for example Ratchet PHP, you'll see that the thing which handles the WebSocket requests receives a GuzzleHttp object, after the connection is successfully negotiated, in the onOpen callback handler. This contains all of the original HTTP request information tied to the client's connection object so you can continue to use that throughout.

So essentially a Connection object holds all of the information about the sateful TCP socket itself, coupled with the HTTP object, which could be implemented as something like a GuzzleHttp or PSR7 Message object. Each time a message is received from that Connection object, the coupled HTTP object can be access to lookup the related request line from the initial HTTP request.

Upvotes: 3

kelunik
kelunik

Reputation: 6928

A WebSocket connection is established using an HTTP GET request that upgrades the connection. You can identify clients based on the resource ID in PHP by casting the resource to an integer using (int) $resource.

TCP connections in general are identified by the source IP / source port / destination IP / destination port quadruple.

You have to keep the URI / endpoint info in an array or similar data structure and use the client ID as index. Then you can look up the endpoint upon receiving new messages.

Upvotes: 1

Related Questions