【问题标题】:How to response to all clients with websocket?如何使用 websocket 响应所有客户端?
【发布时间】:2014-03-04 10:51:42
【问题描述】:

我正在使用 PHP-Websocket 开发一个小项目。

服务器端正在使用这个https://github.com/ghedipunk/PHP-Websockets运行

服务器端:

require "PHP-Websockets/websockets.php";

class Server extends WebSocketServer
{
    private $_connecting = 'Connecting..';
    private $_welcome = 'SOCKET SERVER!';


    protected function connected($user)
    {
        // Send welcome message to user when connected

    }    



    protected function process($user, $message)
    {
        // data sent from client
        $json = json_decode($message);

        //prepare data response to client
        $response = json_encode(array('type'=>'notify', 'message'=>'Client'.$user->id.' has sent a request.'));
        $this->send($user, $response);
    }

    protected function closed($user)
    {
        // Alert on server
        echo "User $user->id has closed the connection".PHP_EOL;
    }

    public function __destruct()
    {
        echo "Server Closed!".PHP_EOL;
    }
}

$addr = 'localhost';
$port = '2207';
$server = new Server($addr, $port);
$server->run();

客户端:

<script>
var uri = "ws://localhost:2207";
function socket_connect(){
    socket = new WebSocket(uri);
    if(!socket || socket == undefined) return false;

    socket.onopen = function(){
        console.log('Connected to Server!');
    }

    socket.onerror = function(){
        console.log('Connection Failed!');
    }

    socket.onclose = function(){
        socket_log('Connection Closed! ')
    }

    socket.onmessage = function(e){
        //var response_data = e.data;
        var msg = JSON.parse(e.data); //PHP sends Json data to client
        console.log(msg.message);
        var new_response = '<li>'+msg.message+'</li>;
        $('#response').append(new_response);
    }
}

function send_data_to_server(data){
    if(!socket || socket == undefined) return false;
    socket.send(JSON.stringify(data));
}

$(document).ready(function(){
    socket_connect();


    $('#send_request').click(function(){
        send_data_to_server({message: 'Message sent from Client'});
    });
});
</script>

<input type="button" id="send_request" value="Send Request to Server" />

<ul id="responses"></ul>

上面的代码一切正常。

当 Client1 向 Server 发送请求时,Server 会立即响应他。但是其他客户端看不到响应消息。

所以我想让它更进一步:当客户端向服务器发送请求时,服务器将响应 ALL 客户端,以便所有客户端都能看到消息。

我该怎么做?

提前感谢&&对不起我的英语不好!

【问题讨论】:

  • 根据this guide,可能已经有一个WebSocketServer::$users 可遍历变量foreach
  • 我知道这是旧的,但是 ghedipunk api 是如何为您工作的?我现在正在考虑将它用于基本的 Web 套接字应用程序。有没有人在这个线程上找到了更好的?

标签: php websocket phpwebsocket


【解决方案1】:

当用户连接时,您需要将他与其他所有用户一起添加到数组中。 当一个人断开连接时,将他从这个数组中移除。

然后,当您想向每个用户发送消息时,迭代数组并将消息发送给每个连接的用户。

【讨论】:

    【解决方案2】:
    WebSocketServer class has WebSocketServer::$users variable.
    

    如果您在split_packet 函数中迭代WebSocketServer::$users,然后调用主进程,它将起作用。在最新的源代码中,请在第 405 行进行迭代。

    //original
    if ((preg_match('//u', $message)) || ($headers['opcode']==2)) {
            //$this->stdout("Text msg encoded UTF-8 or Binary msg\n".$message); 
            $this->process($user, $message);
          } else {
            $this->stderr("not UTF-8\n");
          }
    

    //必须改变

    if ((preg_match('//u', $message)) || ($headers['opcode']==2)) {
            //$this->stdout("Text msg encoded UTF-8 or Binary msg\n".$message); 
            foreach($this->users as $usr){
                $this->process($usr, $message);
            }
          } else {
            $this->stderr("not UTF-8\n");
          }
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2018-05-23
      • 2020-02-11
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      相关资源
      最近更新 更多