swoole 客户端和服务端不断通信

server.php

<?php
class Chat
{
    const HOST = '0.0.0.0';//ip地址 0.0.0.0代表接受所有ip的访问
    const PART = 9501;//端口号

    private $server = null;//单例存放websocket_server对象

    public function __construct()
    {
        //实例化swoole_websocket_server并存储在我们Chat类中的属性上,达到单例的设计
        $this->server = new swoole_websocket_server(self::HOST, self::PART);
        //监听连接事件
        $this->server->on('open', [$this, 'onOpen']);
        //监听接收消息事件
        $this->server->on('message', [$this, 'onMessage']);
        //监听关闭事件
        $this->server->on('close', [$this, 'onClose']);
        //设置允许访问静态文件


        //开启服务
        $this->server->start();
    }

    /**
     * 连接成功回调函数
     * @param $server
     * @param $request
     */
    public function onOpen($server, $request)
    {
        echo $request->fd . '连接了' . PHP_EOL;//打印到我们终端
        $server->push($request->fd,"服务端收到你的连接了");
    }

    /**
     * 接收到信息的回调函数
     * @param $server
     * @param $frame
     */
    public function onMessage($server, $frame)
    {
        var_dump("收到客户端消息:".$frame->data);
        $server->push($frame->fd, "服务端收到你的消息了".$frame->data);
        Swoole\Timer::tick(1000, function() use($server,$frame){
            $server->push($frame->fd, "当前时间".date("Y-m-d H:i:s"));
        });

    }

    /**
     * 断开连接回调函数
     * @param $server
     * @param $fd
     */
    public function onClose($server, $fd)
    {
        echo $fd . '走了' . PHP_EOL;//打印到我们终端
    }

}

$obj = new Chat();

  

index.html

<!--ws_client.html-->
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>
<h1>模拟Web Socket客户端·向服务端投递Task任务</h1>
<script>
    var wsUrl = "ws://192.168.40.10:9501";
    var webSocket = new WebSocket(wsUrl);

    //实例化JavaScript连接事件
    webSocket.onopen = function(evt){
        webSocket.send("我正在模拟向服务端发送消息");
        console.log("连接WebSocket成功!");
    }

    //实例化onmessage
    webSocket.onmessage = function(evt){
        console.log("服务端说:" + evt.data);
    }

    //实例化onclose事件
    webSocket.onclose = function(evt){
        console.log("Web Socket连接关闭");
    }

    //实例化onerror事件
    webSocket.onerror = function(evt,e){
        console.log("好像有些错误:" + evt.data);
    }
</script>

 php server.php

 

猜你喜欢

转载自www.cnblogs.com/php-linux/p/12746511.html