swoole webSocket服務

socket.phpphp

<?php
//建立websocket服務器對象,監聽0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9503);

//監聽WebSocket鏈接打開事件 (剛打開的時候會給客戶端發送 Hello,welcome)
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome\n");
});

//監聽WebSocket消息事件(客戶端互相發送信息)
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");
});

//監聽WebSocket鏈接關閉事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

socket.htmlhtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>socket</title>

</head>
<body>
123
</body>
<script>
    var wsServer = 'ws://192.168.70.167:9503';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (evt) {
        console.log("Connected to WebSocket server.");
    };

    websocket.onclose = function (evt) {
        console.log("Disconnected");
    };

    websocket.onmessage = function (evt) {
        console.log('Retrieved data from server: ' + evt.data);
    };

    websocket.onerror = function (evt, e) {
        console.log('Error occured: ' + evt.data);
    };
</script>
</html>

socket.php,socket.html  目錄/usr/local/nginx/html/下nginx

啓動socket.php:web

# php socket.php

啓動socket.htmljson

瀏覽器打開:192.168.70.167/socket.html瀏覽器

 

 

 

 

其餘寫法:服務器

以循環的方式給每個用戶發送信息websocket

$ws->on('message', function ($ws, $frame) {
    //echo "接收到的信息: {$frame->data}\n";
    //$ws->push($frame->fd, "server: {$frame->data}");
    //echo "服務器已接收:【".$frame->fd."】";
    //$ws->push($frame->fd, json_encode(['hello','world'.$frame->data]));


    // 1.客戶端發送過來的信息
    $content = $frame->data;
    echo "服務器接收到信息:".$content."\n";
    // 2.講消息發送個全部客戶端
    $arr = json_decode($content);
    $id = $arr[0];
    $str= $arr[1];

    //一對一推送
    $ws->push($id,$str);
    // 一對多,推送 (循環方式給每個客戶端發送信息)
    /*foreach ($ws->connections as $fd){
        //echo "FD:".$fd."\n";
        $arr = json_decode($content);
        $id = $arr[0];
        $str= $arr[1];

        $ws->push($fd,$str);
    }*/
});
相關文章
相關標籤/搜索