thinkPHP5扩展workerman

时间:2024-10-29 10:06:32
-安装workerman

首先通过 composer 安装
composer require topthink/think-worker -vvv

  

 如果报错:
Installation failed, reverting ./composer.json to its original cont

  

 则使用
composer require topthink/think-worker=1.0.* -vvv

  

 如果需要在window下做服务端,还需要
composer require workerman/workerman-for-win -vvv

  

-在thinkphp5根目录(即与application同级目录)创建server.php,编辑一下内容。 server.php 文件内容
define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE','push/Worker');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';

  

-新建模块和控制器
创建workerman的controller,命名为Worker.php。在application/push/controller,目录不存在自行创建。添加以下内容:

  

-Worker.php。文件的内容
<?php

namespace app\push\controller;

use think\worker\Server;

class Worker extends Server
{
  protected $socket = 'websocket://127.0.0.1:2346';   /**
  * 收到信息
  * @param $connection
  * @param $data
  */
  public function onMessage($connection, $data)
  {
  $connection->send('我收到你的信息了');
  }   /**
  * 当连接建立时触发的回调函数
  * @param $connection
  */
  public function onConnect($connection)
  {   }   /**
  * 当连接断开时触发的回调函数
  * @param $connection
  */
  public function onClose($connection)
  {   }
  /**
  * 当客户端的连接上发生错误时触发
  * @param $connection
  * @param $code
  * @param $msg
  */
  public function onError($connection, $code, $msg)
  {
    echo "error $code $msg\n";
  }   /**
  * 每个进程启动
  * @param $worker
  */
  public function onWorkerStart($worker)
  {   }
}

  

-运行server.php
命令:php server.php

  

- 新建html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<script>
  ws = new WebSocket("ws://127.0.0.1:2346");
  ws.onopen = function() {
    alert("连接成功");
  ws.send('tom');
    alert("给服务端发送一个字符串:tom");
  };
  ws.onmessage = function(e) {
    alert("收到服务端的消息:" + e.data);
  };
</script>
</body>
</html>

  

 原文:https://blog.****.net/qq_37322178/article/details/83715141 

thinkPHP5扩展workerman