swoole WebSocket 消息推送

 

server.php

<?php
//连接本地的 Redis 服务
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set("fd", "[]");    //每次第一次执行都需要先清空reids里面的标识

 
$server = new swoole_websocket_server("0.0.0.0", 9502);

$server->on('open', function (swoole_websocket_server $server, $request) use($redis) {
    echo "访客{$request->fd}进来了\n";
    $server->push($request->fd, "{$request->fd}客户进来了");
    $str = json_decode($redis->get("fd"), true);
    if($str == "") $str = [];
     if(!in_array($request->fd, $str)){
        array_push($str, $request->fd);
         $str = json_encode($str);
         $redis->set("fd", $str);
         echo "目前在线访客:";
         print_r($redis->get("fd"));
     }
});

$server->on('message', function (swoole_websocket_server $server, $frame) use($redis) {
    echo "系统消息说:{$frame->data}\n";
    $str = json_decode($redis->get("fd"), true);
     foreach ($str as $key => $value) {
         if($frame->fd != $value){
             $server->push($value, "系统消息说:".$frame->data);
         }
     }
});

$server->on('close', function ($ser, $fd) use($redis) {
     echo "client {$fd} closed\n";
     $str = json_decode($redis->get("fd"), true);
     $point = array_keys($str, $fd, true);  //search key
     array_splice($str, $point['0'],1);  //delete array
     $str = json_encode($str);
     $redis->set("fd", $str);
     echo "删除后在线访客:";
     print_r($redis->get("fd"));
});

$server->start();

Cli命令行执行:/usr/local/php/bin/php server.php

 

client.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="main">
    <div class="msgs">
        消息通知:<span id="push_content" style="color:red"></span>
    </div>
</div>
</body>
<script>
    var socket = new WebSocket('ws://23.27.127.32:9502');  //监听端口
    socket.onopen = function () {  //监听是否连接服务器成功触发
        console.log('Connected!');
         //socket.send("这条信息会返回给服务器看");    //重要!!客户端返回服务器
    };
    socket.onmessage = function (event) {  // **接收到服务器数据**触发
        console.log(event.data);
//        alert('Received data: ' + event.data);
        document.getElementById("push_content").innerHTML = event.data;
//        socket.close();
    };
    socket.onclose = function () {  //与服务器连接断开触发
        console.log('Lost connection!');
    };
    socket.onerror = function () { //与服务器连接出现错误触发
        console.log('Error!');
    };
//    socket.send('hello, world!');

</script>
</html>

admin.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>后台推送界面</title>
</head>
<body>
<div>
    <input type="text" name="content" placeholder="请输入需要推送的信息">
    <button id="push_button">推送</button>
</div>
</body>
<script>
    window.onload = function () {
        var socket = new WebSocket('ws://23.27.127.32:9502');  //监听端口
        var push_button = document.getElementById("push_button");
        var push_content = document.getElementsByName("content");

        push_button.onclick = function () {
            socket.send(push_content['0'].value);
        }
        socket.onmessage = function (event) {  // **接收到服务器数据**触发
            // alert('Received data: ' + event.data);   //这里应该返回发送成功的额标识
        };
        socket.onopen = function () {  //监听是否连接服务器成功触发
            console.log('Connected!');
            // socket.send(push_content['0'].value);    //重要!!客户端返回服务器
        };

        socket.onclose = function () {  //与服务器连接断开触发
            console.log('Lost connection!');
        };
        socket.onerror = function () { //与服务器连接出现错误触发
            console.log('Error!');
        };
    };
</script>
</html>

 

 

 

源码下载

 

posted on 2018-01-15 16:21  长不大的菜鸟  阅读(3790)  评论(0编辑  收藏  举报

导航