简体   繁体   中英

How can I send a message to a specific client connected through socket

Hello This is my first time working on sockets. I have multiple clients which connect to my socket server through a specific port. I want to send a specific message to a specific client. how can I do that?.

I am using this library

https://github.com/navarr/Sockets

This is the code

<?php

use Navarr\Socket\Socket;
use Navarr\Socket\Server;

class EchoServer extends Server
{
    const DEFAULT_PORT = 7;

    public function __construct($ip = null, $port = self::DEFAULT_PORT)
    {
        parent::__construct($ip, $port);
        $this->addHook(Server::HOOK_CONNECT, array($this, 'onConnect'));
        $this->addHook(Server::HOOK_INPUT, array($this, 'onInput'));
        $this->addHook(Server::HOOK_DISCONNECT, array($this, 'onDisconnect'));
        $this->run();
    }

    public function onConnect(Server $server, Socket $client, $message)
    {
        echo 'Connection Established',"\n";
    }

    public function onInput(Server $server, Socket $client, $message)
    {
        echo 'Received "',$message,'"',"\n";
        $client->write($message, strlen($message));
    }

    public function onDisconnect(Server $server, Socket $client, $message)
    {
        echo 'Disconnection',"\n";
    }
}

$server = new EchoServer('0.0.0.0');

This line $client->write($message, strlen($message)); will send a message to a client if only one client is connected. but if multiple clients connected then how can I send a message to specific client?

Add this code inside onConnect function.

//declare this as global inside EchoServer class so that you can access this outside onConnect function
$connected_clients["userID"] = $client; //use unique id for key

Then to send message, use the userID to access right client:

$connected_clients["userID"]->write($message, strlen($message));

To get userID , once the client connect to your server request for the client id, example: use JSON for easy communication, send this JSON message

{"messageType":"request", "requestType": "identification"} 

to client. On client side process the message and send this JSON message

{"messageType":"response", 
 "body":{"userID":"123456", "accessToken":"ye5473rgfygf737trfeyg3rt764e"}} 

back to server. On the server side validate the access token and retrieve userID from the response. userID is unique identification number store in database which is assign to each user during there registration to your chat site.

To know the client that send message, use this JSON message format

{"messageType":"message", 
 "from":"userID", 
 "body":"message here"}

Modify to suit your preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM