Event.php 3.0 KB

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