SocketIO.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\http\command;
  3. use think\console\Input;
  4. use think\console\input\Argument;
  5. use think\console\input\Option;
  6. use think\console\Output;
  7. use think\console\Command;
  8. use Workerman\Worker;
  9. use PHPSocketIO\SocketIO as ISocketIO;
  10. use Workerman\Protocols\Http\Request;
  11. use Workerman\Connection\TcpConnection;
  12. /**
  13. * 给指定channel客户端发送消息接口: http://<domain>/publish post: {"channel":"....","content":"...."}
  14. * 给所有客户端发送消息接口: http://<domain>/publish post: {"content":"...."}
  15. * @package app\http\command
  16. */
  17. class SocketIO extends Command
  18. {
  19. /**
  20. * @var object
  21. */
  22. protected $io = null;
  23. /**
  24. * 命令行配置
  25. *
  26. * @author 许祖兴 < zuxing.xu@lettered.cn>
  27. * @date 2020/3/26 20:14
  28. * @return void
  29. */
  30. protected function configure()
  31. {
  32. $this->setName('mni:socket')
  33. ->addArgument('action', Argument::REQUIRED, "start | restart | reload | stop | status | connetions")
  34. ->addOption('mode', '-m', Option::VALUE_OPTIONAL, 'Start in daemon mode or debug mode')
  35. ->setDescription('phpsocket.io');
  36. }
  37. /**
  38. * 执行方法
  39. *
  40. * @author 许祖兴 < zuxing.xu@lettered.cn>
  41. * @date 2020/3/26 20:15
  42. *
  43. * @param Input $input
  44. * @param Output $output
  45. * @return int|void|null
  46. */
  47. protected function execute(Input $input, Output $output)
  48. {
  49. global $argv;
  50. // 命令行适配 linux
  51. $argv[1] = $input->getArgument('action'); // start | restart | reload(平滑重启) | stop | status | connetions
  52. // die;
  53. // 默认执行模式
  54. if (!empty($input->getOption('mode'))){
  55. if (!in_array($input->getOption('mode'),['daemon','debug'])){
  56. $output->writeln('mode must be daemon or debug');
  57. die;
  58. }
  59. $argv[2] = '-d';
  60. }
  61. // PHPSocketIO服务
  62. $this->io = new ISocketIO(2120);
  63. $this->io->on('connection', function($socket) {
  64. $socket->on('disconnect', function () use($socket) {
  65. });
  66. });
  67. // 当$sender_io启动后监听一个http端口,通过这个端口可以给任意uid或者所有uid推送数据
  68. $this->io->on('workerStart', function(){
  69. // 监听一个http端口
  70. $inner_http_worker = new Worker('http://0.0.0.0:2121');
  71. // 当http客户端发来数据时触发
  72. $inner_http_worker->onMessage = function(TcpConnection $http_connection, Request $request){
  73. $post = $request->post();
  74. $post = $post ? $post : $request->get();
  75. // 推送处理
  76. if (!empty($post )){
  77. $this->io->emit('message', $post);
  78. return $http_connection->send('ok');
  79. }
  80. return $http_connection->send('fail');
  81. };
  82. // 执行监听
  83. $inner_http_worker->listen();
  84. });
  85. Worker::runAll();
  86. }
  87. }