简体   繁体   English

Php 套接字编程向单个客户端发送消息

[英]Php socket programming send message to single client

I'm trying to create a live support chat.我正在尝试创建实时支持聊天。 I need to send message to single client with socket programming.我需要使用套接字编程向单个客户端发送消息。

$host = "127.0.0.1";
$port = 20205;

$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket");
$result = socket_bind($sock, $host, $port) or die ("Could not bind to socket");

$result = socket_listen($sock, 3) or die ("Could not set up socket listener");

echo "Connection Established";

do{
    $accept = socket_accept($sock) or die("Could not accept incoming connection");
    $msg = socket_read($accept, 1024) or die("Could not read input");

    $msg = trim($msg);
    echo "Client says: \t".$msg."\n\n";

    $reply = '{
        "text":"test message"
        "chatid":1
    }';

    socket_write($accept, $reply, strlen($reply)) or die("Could not write output");
}while(true);
socket_close($accept, $sock);

I'm sending message like this.我正在发送这样的消息。 How can I send message to single client.如何向单个客户端发送消息。

I think you need to support multiple connections after that, you will response depend on each sent data from client, please check PHP Sockets - Accept multiple connections and https://www.php.net/manual/en/function.socket-accept.php我认为您需要支持多个连接,您将根据客户端发送的每个数据进行响应,请检查PHP Sockets - Accept multiple connectionsZ5E056C500A1C4B6A7110B50D807BADEen5Z://www.-accept.net/function. .php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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