I\'m trying to build a system where user can subscribe to a category on establishing connection to websocket server and then he will start receiving updates for that category. S
ok, now I am sharing my experience. You Can Send Token and Insert This toke in onOpen (server.php) in the database. You can Insert Chat Token When User Login. Every Time When User Login New Token is generated and updated. Now Use This Token To Find out user Id in onOpen connection.
var conn = new WebSocket('ws://172.16.23.26:8080?token=');
conn.onopen = function(e) {
console.log("Connection established!");
};
Now Server.php
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$querystring = $conn->httpRequest->getUri()->getQuery();
parse_str($querystring,$queryarray);
//Get UserID By Chat Token
$objUser = new \users;
$objUser->setLoginToken($queryarray['token']);
$GetUserInfo = $objUser->getUserByToken();
echo "New connection! ({$conn->resourceId})\n";
//save Chat Connection
// Insert the new connection with the user ID to Match to later if user ID in Table Then Update IT with a new connection
}
Now your Connection is established, then send Message To particular users
Client-Side send USerID with received ID and Message
$("#conversation").on('click', '#ButtionID', function () {
var userId = $("#userId").val();
var msg = $("#msg").val();
var receiverId = $("#receiverId").val();
if ( userId != null && msg != null ){
var data = {
userId: userId,
msg: msg,
receiverId: receiverId
};
conn.send(JSON.stringify(data));
$("#msg").val("");
}
});
Server Side
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n",$from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
$data = json_decode($msg, true);
echo $data['userId'];
echo $data['msg'];
echo $data['receiverId'];
// Save User ID receiver Id message in table
//Now Get Chat Connection by user id By Table Which is saved onOpen function
$UptGetChatConnection = $objChatroom->getChatConnectionUserID($data['receiverId']);
$ReciId = $UptGetChatConnection[0]['ConnectionID'];
foreach ($this->clients as $client) {
if ($from == $client) {
$data['from'] = "Me";
$data['fromname'] = 5;
} else {
$data['from'] = $user['name'];
$data['fromname'] = 6;
}
echo $client->resourceId;
echo $ReciId."\n";
if($client->resourceId == $ReciId || $from == $client){
$client->send(json_encode($data));
}
}
}
now the message has been sending by connection ID not broadcast only send particular users