ChatClient.php 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace App\Services\Socket;
  3. use Ratchet\MessageComponentInterface;
  4. use Ratchet\ConnectionInterface;
  5. class ChatClient implements MessageComponentInterface
  6. {
  7. protected $clients;
  8. public function __construct()
  9. {
  10. $this->clients = new \SplObjectStorage;
  11. }
  12. public function onOpen(ConnectionInterface $conn)
  13. {
  14. $this->clients->attach($conn);
  15. echo "SocketClient:创建连接【{$conn->resourceId}】成功! \n";
  16. }
  17. public function onMessage(ConnectionInterface $from, $msg)
  18. {
  19. echo "SocketClient:收到消息 ".$msg.'++'.$from->resourceId."\n";
  20. $from->send($msg);
  21. }
  22. public function onClose(ConnectionInterface $conn)
  23. {
  24. $this->clients->detach($conn);
  25. echo "SocketClient:关闭连接【{$conn->resourceId}】成功\n";
  26. }
  27. public function onError(ConnectionInterface $conn, \Exception $e)
  28. {
  29. echo "SocketClient:连接错误 {$e->getMessage()}\n";
  30. $conn->close();
  31. }
  32. }