server.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. header("Access-Control-Allow-Origin: *");
  3. require 'vendor/autoload.php';
  4. use Ratchet\MessageComponentInterface;
  5. use Ratchet\ConnectionInterface;
  6. use Ratchet\Server\IoServer;
  7. use Ratchet\Http\HttpServer;
  8. use Ratchet\WebSocket\WsServer;
  9. // 自定义 WebSocket 处理类
  10. class MyWebSocketHandler implements MessageComponentInterface {
  11. protected $clients;
  12. public function __construct() {
  13. $this->clients = new \SplObjectStorage();
  14. }
  15. // 当新客户端连接时触发
  16. public function onOpen(ConnectionInterface $conn) {
  17. $this->clients->attach($conn);
  18. echo "新客户端连接: {$conn->resourceId}\n";
  19. }
  20. // 收到客户端消息时触发
  21. public function onMessage(ConnectionInterface $from, $msg) {
  22. echo "收到消息: $msg\n";
  23. //将消息发送给所有用户
  24. foreach ($this->clients as $client) {
  25. $client->send($msg);
  26. }
  27. // 原样回复客户端
  28. //$from->send("服务器回复: $msg");
  29. // 收到 "exit" 时关闭连接
  30. if ($msg === 'exit') {
  31. $from->close();
  32. }
  33. }
  34. // 当客户端断开时触发
  35. public function onClose(ConnectionInterface $conn) {
  36. $this->clients->detach($conn);
  37. echo "客户端断开: {$conn->resourceId}\n";
  38. }
  39. // 错误处理
  40. public function onError(ConnectionInterface $conn, \Exception $e) {
  41. echo "错误: {$e->getMessage()}\n";
  42. $conn->close();
  43. }
  44. //公共方法
  45. public function curlPost($url,$data){
  46. // 初始化 cURL
  47. $ch = curl_init();
  48. // 设置 cURL 选项
  49. curl_setopt($ch, CURLOPT_URL, $url); // 设置 URL
  50. curl_setopt($ch, CURLOPT_POST, true); // 设置为 POST 请求
  51. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 设置 POST 数据
  52. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回结果保存到变量而不是直接输出
  53. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  54. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
  55. // 执行请求并获取响应
  56. $response = curl_exec($ch);
  57. // 检查是否有错误发生
  58. if(curl_errno($ch)){
  59. echo 'cURL 错误: ' . curl_error($ch);
  60. }
  61. // 关闭 cURL 资源并释放内存
  62. curl_close($ch);
  63. // 处理响应数据(如果需要)
  64. return $response;
  65. }
  66. //将对象转为数组
  67. public function stdClassObjToArray($array) {
  68. if(is_object($array)) {
  69. $array = (array)$array;
  70. }
  71. if(is_array($array)) {
  72. foreach($array as $key=>$value) {
  73. $array[$key] = $this->stdClassObjToArray($value);
  74. }
  75. }
  76. return $array;
  77. }
  78. }
  79. // 创建 WebSocket 服务器(监听 8033 端口)
  80. $server = IoServer::factory(
  81. new HttpServer(new WsServer(new MyWebSocketHandler())),
  82. 8023,
  83. '0.0.0.0' // 明确指定监听所有接口
  84. );
  85. echo "WebSocket 服务器已启动 (端口 8023)...\n";
  86. $server->run();