Event.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * 聊天逻辑,使用的协议是 文本+回车
  4. * 测试方法 运行
  5. * telnet ip 8480
  6. * 可以开启多个telnet窗口,窗口间可以互相聊天
  7. *
  8. * websocket协议的聊天室见workerman-chat及workerman-todpole
  9. * @author walkor <workerman.net>
  10. */
  11. use \Lib\Context;
  12. use \Lib\Gateway;
  13. use \Lib\StatisticClient;
  14. use \Lib\Store;
  15. use \Protocols\GatewayProtocol;
  16. use \Protocols\TextProtocol;
  17. class Event
  18. {
  19. /**
  20. * 当网关有客户端链接上来时触发,一般这里留空
  21. */
  22. public static function onGatewayConnect()
  23. {
  24. Gateway::sendToCurrentClient(TextProtocol::encode("type in your name:"));
  25. }
  26. /**
  27. * 网关有消息时,判断消息是否完整
  28. */
  29. public static function onGatewayMessage($buffer)
  30. {
  31. return TextProtocol::check($buffer);
  32. }
  33. /**
  34. * 有消息时触发该方法
  35. * @param int $client_id 发消息的client_id
  36. * @param string $message 消息
  37. * @return void
  38. */
  39. public static function onMessage($client_id, $message)
  40. {
  41. $message_data = TextProtocol::decode($message);
  42. // **************如果没有$_SESSION['name']说明没有设置过用户名,进入设置用户名逻辑************
  43. if(empty($_SESSION['name']))
  44. {
  45. $_SESSION['name'] = TextProtocol::decode($message);
  46. Gateway::sendToCurrentClient("chart room login success, your client_id is $client_id, name is {$_SESSION['name']}\nuse client_id:words send message to one user\nuse words send message to all\n");
  47. // 广播所有用户,xxx come
  48. return GateWay::sendToAll(TextProtocol::encode("{$_SESSION['name']}[$client_id] come"));
  49. }
  50. // ********* 进入聊天逻辑 ****************
  51. // 判断是否是私聊
  52. $explode_array = explode(':', $message, 2);
  53. // 私聊数据格式 client_id:xxxxx
  54. if(count($explode_array) > 1)
  55. {
  56. $to_client_id = (int)$explode_array[0];
  57. GateWay::sendToClient($client_id, TextProtocol::encode($_SESSION['name'] . "[$client_id] said said to [$to_client_id] :" . $explode_array[1]));
  58. return GateWay::sendToClient($to_client_id, TextProtocol::encode($_SESSION['name'] . "[$client_id] said to You :" . $explode_array[1]));
  59. }
  60. // 群聊
  61. return GateWay::sendToAll(TextProtocol::encode($_SESSION['name'] . "[$client_id] said :" . $message));
  62. }
  63. /**
  64. * 当用户断开连接时触发的方法
  65. * @param integer $client_id 断开连接的用户id
  66. * @return void
  67. */
  68. public static function onClose($client_id)
  69. {
  70. // 广播 xxx 退出了
  71. GateWay::sendToAll(TextProtocol::encode("{$_SESSION['name']}[$client_id] logout"));
  72. }
  73. }