| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace app\http\command;
- use think\console\Input;
- use think\console\input\Argument;
- use think\console\input\Option;
- use think\console\Output;
- use think\console\Command;
- use Workerman\Worker;
- use PHPSocketIO\SocketIO as ISocketIO;
- use Workerman\Protocols\Http\Request;
- use Workerman\Connection\TcpConnection;
- /**
- * 给指定channel客户端发送消息接口: http://<domain>/publish post: {"channel":"....","content":"...."}
- * 给所有客户端发送消息接口: http://<domain>/publish post: {"content":"...."}
- * @package app\http\command
- */
- class SocketIO extends Command
- {
- /**
- * @var object
- */
- protected $io = null;
- /**
- * 命令行配置
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/3/26 20:14
- * @return void
- */
- protected function configure()
- {
- $this->setName('mni:socket')
- ->addArgument('action', Argument::REQUIRED, "start | restart | reload | stop | status | connetions")
- ->addOption('mode', '-m', Option::VALUE_OPTIONAL, 'Start in daemon mode or debug mode')
- ->setDescription('phpsocket.io');
- }
- /**
- * 执行方法
- *
- * @author 许祖兴 < zuxing.xu@lettered.cn>
- * @date 2020/3/26 20:15
- *
- * @param Input $input
- * @param Output $output
- * @return int|void|null
- */
- protected function execute(Input $input, Output $output)
- {
- global $argv;
- // 命令行适配 linux
- $argv[1] = $input->getArgument('action'); // start | restart | reload(平滑重启) | stop | status | connetions
- // die;
- // 默认执行模式
- if (!empty($input->getOption('mode'))){
- if (!in_array($input->getOption('mode'),['daemon','debug'])){
- $output->writeln('mode must be daemon or debug');
- die;
- }
- $argv[2] = '-d';
- }
- // PHPSocketIO服务
- $this->io = new ISocketIO(2120);
- $this->io->on('connection', function($socket) {
- $socket->on('disconnect', function () use($socket) {
- });
- });
- // 当$sender_io启动后监听一个http端口,通过这个端口可以给任意uid或者所有uid推送数据
- $this->io->on('workerStart', function(){
- // 监听一个http端口
- $inner_http_worker = new Worker('http://0.0.0.0:2121');
- // 当http客户端发来数据时触发
- $inner_http_worker->onMessage = function(TcpConnection $http_connection, Request $request){
- $post = $request->post();
- $post = $post ? $post : $request->get();
- // 推送处理
- if (!empty($post )){
- $this->io->emit('message', $post);
- return $http_connection->send('ok');
- }
- return $http_connection->send('fail');
- };
- // 执行监听
- $inner_http_worker->listen();
- });
- Worker::runAll();
- }
- }
|