利用php的swoole简单实现了webSocket(入门菜鸟)

  • Post author:
  • Post category:php


首先,我在我服务器上照着官方的教程安装了swoole扩展,不容易啊,中间出现了很多波折,php装的版本还是一个大问题,enjoy the process to install swoole extension.

Swoole官方链接:

https://www.swoole.com/


文档链接:

https://wiki.swoole.com/


webSocket链接:

https://wiki.swoole.com/wiki/page/397.html

下面是我写的服务器上面的ws.php(其实就是拷贝一下官方的例子就行):

<?php
$server = new swoole_websocket_server("0.0.0.0",9200);

$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}";
   echo "opcode:{$frame->opcode}";
   echo "fin: {$frame->finish}\n";
   $server->push($frame->fd,"this is a server");
});

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

$server->start();
?>

这里我设置的是0.0.0.0,为的是可以远程访问,如果你是在自己电脑上安装了PHP环境并且安装了swoole扩展,可以直接使用localhost,端口我设置的是9200,你可以设置为一个你想设置的端口,只要不和现有的端口冲突就行。

这样的话,我在服务器上面运行这个文件:

php ws.php

这样服务器上面就正在运行一个swoole server,等待着客户端的连接请求。

OK,做到这里你已经成功了一大半了,很棒的说!


下面就是测试了,这很有趣的,因为你吃了很多苦头,现在正是收货的时候了哈哈。

本地新建文件testWebSocket.html,上代码:

<!doctype html>
<html>
<head>
   <title>测试WebSocket</title>
</head>

<body>
    <script>
        var ws = new WebSocket("ws://120.79.70.19:9200");
        ws.onopen = function(event){
           console.log("客户端已连接上!");
           ws.send("hello server,this is client!");
        };
        ws.onmessage= function(event){
           console.log("服务器传过来的数据是:"+event.data);
        }

        ws.onclose = function(event){
            console.log("连接已关闭");
        };
    </script>
</body>

</html>

写完之后执行在浏览器打开这个html文件,打开console,你就会看到:

这里写图片描述

成功!

祝贺!

我们再来看看服务器上:

这里写图片描述

我们可以看到先建立连接也就是握手然后收到客户端发来的消息,然后给客户端回了消息,然后浏览器关闭了html文件的时候就代表这个连接已经关闭。

我刚开始接触websocket,认为应该就是服务器可以主动给客户端发消息了吧。啃书去…


end.



版权声明:本文为lcr_happy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。