swoole简单入门

版权声明:转发原创文章请复制文章链接地址 https://blog.csdn.net/weixin_42579642/article/details/85125056

Linux下载安装:

git clone https://github.com/swoole/swoole-src.git && \
cd swoole-src && \
phpize && \
./configure && \
make && make install

假设以nginx为web服务器:

创建WebSocket服务器

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

$server->on('open', function (swoole_websocket_server $server, $request) {
    file_put_contents('a.log',$request->fd."\r\n",FILE_APPEND);
    echo "server: handshake success with fd{$request->fd}\n";
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    $arr = file('a.log');
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($arr[array_rand($arr)], "this is server,发送者".$frame->fd);
});

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

$server->start();

创建客户端代码

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>phpLuo</title>
	
      <script type="text/javascript">
          var ws = new WebSocket("ws://自己ip:9501");
          ws.onopen = function() {
            // Web Socket 已连接上
            console.log('连接成功...')
          }
          ws.onclose = function()
          {
              // 关闭 websocket
              alert("连接已关闭...");
          };
          ws.onmessage = function (evt)
          {
              var received_msg = evt.data;
              console.log(evt.data)
          };
         function WebSocketTest()
         {
            //使用 send() 方法发送数据
            ws.send("发送数据");
            alert("数据发送中...");
         }
      </script>
		
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>

服务器端启动WebSocket服务器,php WebSocket服务器的路径如:

php web_sorcket.php

客户端点击

打开控制台即可看到消息,本文中在a.log文件中记录了fd随机在其中随机取,也就是多开几个客户端发的消息会随机发给某个客户端!!!

猜你喜欢

转载自blog.csdn.net/weixin_42579642/article/details/85125056
今日推荐