Jegan
Jegan

Reputation: 595

Send extra information on Websocket connection creation

Currently i'm working on Websocket, and i need to send the some data like user id while made a Websocket connection. And i found the solution such as we can send the value at the end of the Websocket connection url

ws:/localhost:10001/websocket/server.php/456

But they use Node.js in their code. They read the 456 by

websocket.upgradeReq.url

How to do without Node.js. It will send the out value 456 in the Request URL of the http request. And my doubt is how to read that value in server.php. Here server.php handle all the client requests by my custom logic. And i'm try to assign the socket connection which created in server.php to the current value parameter(456) like

$clients['456'] = $socketConnection;

Can any one please give the solution. Thanks in advance

Upvotes: 1

Views: 1183

Answers (1)

Jegan
Jegan

Reputation: 595

After long time i got the solution to my question. The code flow is

1.When i'm initiate a new Websocket connection the server.php accept the connection and manages the client connections in array

$socket_new = socket_accept($socket); //accept new socket
$clients[] = $socket_new; //add socket to client array

2.And send the socket accept message to the client

@socket_write($socket_new ,$msg,strlen($msg));//$msg in object format

3.When the client receives message from Websocket server, i'm sending the client id to server

 ws.onMessage = function(event){
      ws.send(JSON.stringify({message:'clientRegistration',userId: 456}));
 }

4.In server.php i write my custom logic to handle all client requests. And when the message received by the server the code works like below

while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
        $received_text = unmask($buf); //unmask data
        $tst_msg = json_decode($received_text); //json decode
        if($tst_msg){
            $message = $tst_msg->message; //message text                
            if($message == 'clientRegistration'){
                $clients[$tst_msg->userId] = $changed_socket;
             }
             //you can add your own code here
         }
}

5.Finally i'm having all the client connections in my finger. If i want to send the information to the client '457' means use the code below

@socket_write($clients[457],$msg,strlen($msg));//$msg in object format

Upvotes: 2

Related Questions