Php 如何向通过套接字连接的特定客户端发送消息
你好,这是我第一次使用套接字。我有多个客户端通过特定端口连接到套接字服务器。我想向特定客户发送特定消息。我该怎么做 我在用这个 这是密码Php 如何向通过套接字连接的特定客户端发送消息,php,sockets,Php,Sockets,你好,这是我第一次使用套接字。我有多个客户端通过特定端口连接到套接字服务器。我想向特定客户发送特定消息。我该怎么做 我在用这个 这是密码 <?php use Navarr\Socket\Socket; use Navarr\Socket\Server; class EchoServer extends Server { const DEFAULT_PORT = 7; public function __construct($ip = null, $port = se
<?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');
将此代码添加到onConnect函数中
//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
然后,要发送消息,请使用userID
访问正确的客户端:
$connected_clients["userID"]->write($message, strlen($message));
要获取userID
,一旦客户机连接到您的服务器请求客户机id,例如:使用JSON方便通信,发送此JSON消息
{"messageType":"request", "requestType": "identification"}
{"messageType":"response",
"body":{"userID":"123456", "accessToken":"ye5473rgfygf737trfeyg3rt764e"}}
给客户。在客户端处理消息并发送此JSON消息
{"messageType":"request", "requestType": "identification"}
{"messageType":"response",
"body":{"userID":"123456", "accessToken":"ye5473rgfygf737trfeyg3rt764e"}}
返回服务器。在服务器端,验证访问令牌并从响应中检索userID
userID
是数据库中存储的唯一标识号,在注册到聊天网站期间分配给每个用户
要了解发送消息的客户机,请使用此JSON消息格式
{"messageType":"message",
"from":"userID",
"body":"message here"}
根据您的喜好进行修改。您需要在会话中跟踪用户。
?然后分别向他们发送反馈你好,谢谢你的回答。我有一个问题。我如何知道该客户机是我正在寻找的客户机,并向该特定客户机发送数据。我的意思是,在OnConnect函数中,我正在接收资源id。但是我如何才能识别用户。客户端是否必须从其端发送一些我必须在OnConnect函数中获取的内容?或者另一种方法是,我将要求一个客户端发送一些特定的字符串,例如“helloworld”在onInput函数中,我将检查helloworld字符串。但是,我怎样才能确定哪个用户向我发送了hello world文本,所以我根据iti向他发送了回复我编辑了答案以反映您知道的问题非常感谢。如果我有任何其他问题,我可以在这里再次问你关于同一topinc的问题吗?