lis_socket_io.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Protocols\Http\Request;
  4. include __DIR__ . '/vendor/autoload.php';
  5. // 启动tcp端口
  6. $tcp_worker = new Worker('tcp://127.0.0.1:2220');
  7. $tcp_worker->onWorkerStart = function()
  8. {
  9. // 启动http端口(用来主动推送)
  10. $http_worker = new Worker('http://127.0.0.1:2221');
  11. $http_worker->onMessage = function ($connection, Request $request){
  12. $post = $request->post();
  13. $post = $post ? $post : $request->get();
  14. $msg_data = isset($post['data']) ? $post['data'] : false;
  15. global $tcp_worker;
  16. if($msg_data && count($tcp_worker->connections) > 0){
  17. // 获取tcp Worker 实例
  18. foreach($tcp_worker->connections as $tcp_connection)
  19. {
  20. $tcp_connection->send($msg_data);
  21. }
  22. return $connection->send('发送成功!内容:' . $msg_data);
  23. }
  24. return $connection->send('发送失败!');
  25. };
  26. // 监听http
  27. $http_worker->listen();
  28. };
  29. // 当接收到tcp客户端请求时
  30. $tcp_worker->onMessage = function ($connection, $data){
  31. $msg = doEncoding($data);
  32. $msg_data = date('Y-m-d H:i:s') . '接收消息:' . $msg . PHP_EOL . PHP_EOL;
  33. file_put_contents('./data.txt', $msg_data, FILE_APPEND);
  34. $connection->send(date('Y-m-d H:i:s').'----收到消息:' . $msg);
  35. };
  36. /**
  37. * 将socket接收到的乱码字符转为UTF-8字符
  38. * @param string $str
  39. * @return string
  40. */
  41. function doEncoding($str)
  42. {
  43. $encode = strtoupper(mb_detect_encoding($str, ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']));
  44. if ($encode != 'UTF-8') {
  45. $str = mb_convert_encoding($str, 'UTF-8', $encode);
  46. }
  47. return $str;
  48. }
  49. // 运行worker
  50. Worker::runAll();