swoole-websocket

PHP技术
561
0
0
2022-11-02
<?php
$server = new swoole_websocket_server("0.0.0.0", 9503);
$server->on('open', 'onOpen');

$server->set([
    'enable_static_handler' => true,
    'document_root' => '/home/malina/project/swoole/static'
]);
function onOpen($server, $request) {
    print_r($request->fd);
}

$server->on('message', function (swoole_websocket_server $server, $frame){
    echo "receive from {$frame->fd}:{$frame->data}.opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "this is serve");
});

$server->on('close', function ($server, $fd){
    echo $fd . '退出';
});

$server->start();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    ws-test
</body>
<script>
    var wsUrl = "ws://127.0.0.1:9503";
    var websockt = new WebSocket(wsUrl)
    //实例对象的onopen属性
    websockt.onopen = function (evt) {
        console.log("connect-sucess")
    }
    //实例化onmessage
    websockt.onmessage = function (evt) {
        console.log("ws-server-return-data:"+evt.data);
    }

    websockt.onclose = function (evt, e){
        console.log("close:"+evt.data);
    }
</script>
</html>
打开浏览器console 和network 查看
<?php


class Ws{
    const HOST ="127.0.0.1";
    const PORT = 9504;
    public $ws;

    public function __construct() {
        $this->ws = new swoole_websocket_server("0.0.0.0", self::PORT);
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => '/home/malina/project/swoole/static'
        ]);
        $this->ws->on("open", [$this, "onOpen"]);
        $this->ws->on("message", [$this, "onMessage"]);
        $this->ws->on("close", [$this, "onClose"]);
        $this->ws->start();
    }

    /**
     *
     */ 
    public function onOpen($ws, $request){
        print_r($request->fd);
    }

    public function onMessage($ws, $frame) {
        echo "ser-push-msg:{$frame->data}\n";
        $ws->push($frame->fd, "sev-push:".date("Y-md H:i:s"));
    }

    public function onClose($ws, $fd) {
        echo "client:{$fd}";
    }
}

$obj = new Ws();