使用自定义的服务类的形式
运行php think swoole:server
响应Starting swoole server...
然后就没有然后呢?卡住不动了,并没有像默认配置的一样提示启动成功
swoole_server.php
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\facade\Env;
// +----------------------------------------------------------------------
// | Swoole设置 php think swoole:server 命令行下有效
// +----------------------------------------------------------------------
return [
// 扩展自身配置
'host' => '0.0.0.0', // 监听地址
'port' => 9508, // 监听端口
'type' => 'socket', // 服务类型 支持 socket http server
'mode' => '', // 运行模式 默认为SWOOLE_PROCESS
'sock_type' => '', // sock type 默认为SWOOLE_SOCK_TCP
'swoole_class' => 'app\socket\Swoole', // 自定义服务类名称
// 可以支持swoole的所有配置参数
'daemonize' => false,
'pid_file' => Env::get('runtime_path') . 'swoole_server.pid',
'log_file' => Env::get('runtime_path') . 'swoole_server.log',
// 事件回调定义
'onOpen' => function ($server, $request) {
echo "server: handshake success with fd{$request->fd}\n";
},
'onMessage' => function ($server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "this is server");
},
'onRequest' => function ($request, $response) {
$response->end("<h1>Hello Swoole. #" . rand(1000, 9999) . "</h1>");
},
'onClose' => function ($ser, $fd) {
echo "client {$fd} closed\n";
},
];Swoole.php<?php
namespace app\socket;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\swoole\Server;
class Swoole extends Server{
protected $host = '0.0.0.0';
protected $port = 2346;
protected $serverType = 'socket';
/**
* 监听WebSocket消息事件
* @param $ws Swoole\Server 对象
* @param $frame 是 Swoole\WebSocket\Frame 对象,包含了客户端发来的数据帧信息
*/
public function onMessage($ws, $frame){
echo "Message: {$frame->data}\n";
}
/**
* 监听WebSocket连接打开事件
* @param $ws Swoole\Server 对象
* @param $request 是一个 HTTP 请求对象,包含了客户端发来的握手请求信息
*/
public function onOpen($ws, $request){
var_dump($request->fd, $request->get, $request->server);
}
/**
* 监听WebSocket连接关闭事件
* @param $ws Swoole\Server 对象
* @param $fd 连接的文件描述符
*/
public function onClose($ws, $fd){
var_dump("close connection id:".$fd);
}
/**
* 当客户端的连接上发生错误时触发
* @param Swoole\Server $server
* @param $code
* @param $msg
*/
public function onWorkerError($server,$worker_id,$worker_pid,$exit_code,$signal){
var_dump("error: worker_id=>{$worker_id} exit_code=>{$exit_code} signal=>{$signal}");
}
} 最佳答案