龚哥哥 - 山里男儿 爱生活、做自己!
PHP采用Swoole扩展开发高性能WebSocket
发表于 2016-9-17 | 浏览(17004) | PHP

需要安装PHP Swoole扩展,官网地址:http://www.swoole.com/

安装教程可查看本博客中swoole安装

1、index.html 内容如下

<!DOCTYPE html>
<head>
<title>socket demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="./jquery-2.1.3.min.js"></script>
</head>
<body>
<input type="text" id="msg" />
<button id="send">发送</button>
</body>
</html>
<script>
$(function()
{
    // 创建socket对象
    var socket = new WebSocket('ws://'+document.domain+':9501');

    // 打开Socket 
    socket.onopen = function(event)
    {

        $('#send').on('click', function()
        {
            var msg = $('#msg').val();
            socket.send(msg);
            console.log(msg);
        });
        // 发送一个初始化消息
        socket.send("客户端初始化!"); 

        // 监听消息
        socket.onmessage = function(event) { 
            console.log("客户端监听到的消息:", event); 
        }; 

        // 监听Socket的关闭
        socket.onclose = function(event) { 
        console.log("Socket关闭了", event); 
        }; 

      // 关闭Socket.... 
      //socket.close() 
    };
});
</script>

2、web_socket.php 内容如下

<?php

// 本机的ip
// 通过命令行运行 cli
$server = new swoole_websocket_server("192.168.0.110", 9501);

// 握手成功回调
$server->on('open', function(swoole_websocket_server $server, $request)
{
    echo "server: handshake success with fd{$request->fd}\n";
});

// 消息监听
$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 server {$frame->data}");
});

// 关闭监听
$server->on('close', function($ser, $fd)
{
    echo "client {$fd} closed\n";
});

// http请求监听, 如果监听了Request则可以通过http访问
// 通过 http://192.168.0.110:9501 访问
$server->on('Request', function($req, $respone)
{
    // $req->get, $req->post
    if(!empty($req->get))
    {
        // 使用全局变量
        global $server;

        // 服务器推送消息给客户端
        // 参数1 socketID, 参数2 推送内容
        $server->push(1, "this is server hello request {$req->get['msg']}");

        // 响应完成
        $respone->end("success");
    }
});

// 开始
$server->start();

?>

3、在命令行运行web_socket.php

php web_socket

4、客户端在浏览器上访问,可发送消息到服务器并且响应服务器推送的消息

http://192.168.0.110/index.html

5、服务器端推送消息给客户端,在客户端页面可看见推送的消息

http://192.168.0.110:9501?msg=hello

6、测试结果,这里输入什么就给返回什么,在项目中根据自己项目做fid与用户的关联即可。

阅读全文

TOP