首先composer
composer require topthink/think-worker
\config\worker_server.php
return [
// 扩展自身需要的配置
'protocol' => 'websocket', // 协议 支持 tcp udp unix http websocket text
'host' => '0.0.0.0', // 监听地址
'port' => 2346, // 监听端口
// 'socket' => 'http://127.0.0.1:2346', // 完整监听地址
'socket' => '', // 完整监听地址
'context' => [], // socket 上下文选项
'worker_class' => 'app\http\Worker', // 自定义Workerman服务类名 支持数组定义多个服务
去宝塔和云服务器开启2346端口
新建文件夹app\http 创建Woker类
<?php
namespace app\http;
use think\exception\ValidateException;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\facade\Db;
use GatewayWorker\Lib\Gateway;
class Worker extends Server {
protected $socket = 'websocket://0.0.0.0:2346';
protected $uidConnections = array();
public function __construct() {
parent::__construct();
// $this->onWorkerStart();
}
// public function onWorkerStart( $Worker ) {
// //
// }
public function add_timer(){
#设置每60秒执行一次定时任务
/**
*前端启动方式:
// 假设服务端ip为127.0.0.1
ws = new WebSocket("ws://127.0.0.1:2347");
ws.onopen = function() {
alert("连接成功");
};
ws.onmessage = function(e) {
alert("收到服务端的消息:" + e.data);
};
*/
}
public function onConnect($connection) {
$message = [
'app' => 'test',
'yourId' => $connection->id,
];
$connection->send(json_encode($message,JSON_UNESCAPED_UNICODE));
}
/**
* @param $connection
* @param $data 142842567084ds
*/
public function onMessage($connection,$data) {
$message = [
'data' => $data,
'yourId' => $connection->id,
];
$connection->send(json_encode($message,JSON_UNESCAPED_UNICODE));
}
public function sendMsg( $content ) {
if( isset( $content['type'] ) ) {
$type = $content['type'];
$sendId = $content['sendId'];
if( $type == "pushSingle" ) {
Gateway::sendToUid( $sendId, $content['content'] );
}
}
}
}
启动命令
php think worker:server