Event.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 integer $client_id 断开连接的用户id
  36. * @return void
  37. */
  38. public static function onClose($client_id)
  39. {
  40. // 广播 xxx 退出了
  41. GateWay::sendToAll(TextProtocol::encode("{$_SESSION['name']}[$client_id] logout"));
  42. }
  43. /**
  44. * 有消息时触发该方法
  45. * @param int $client_id 发消息的client_id
  46. * @param string $message 消息
  47. * @return void
  48. */
  49. public static function onMessage($client_id, $message)
  50. {
  51. $message_data = TextProtocol::decode($message);
  52. // **************如果没有$_SESSION['name']说明没有设置过用户名,进入设置用户名逻辑************
  53. if(empty($_SESSION['name']))
  54. {
  55. $_SESSION['name'] = TextProtocol::decode($message);
  56. 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");
  57. // 广播所有用户,xxx come
  58. return GateWay::sendToAll(TextProtocol::encode("{$_SESSION['name']}[$client_id] come"));
  59. }
  60. // ********* 进入聊天逻辑 ****************
  61. // 判断是否是私聊,私聊数据格式 client_id:xxxxx
  62. $explode_array = explode(':', $message, 2);
  63. // 私聊
  64. if(count($explode_array) > 1)
  65. {
  66. $to_client_id = (int)$explode_array[0];
  67. GateWay::sendToClient($client_id, TextProtocol::encode($_SESSION['name'] . "[$client_id] said said to [$to_client_id] :" . $explode_array[1]));
  68. return GateWay::sendToClient($to_client_id, TextProtocol::encode($_SESSION['name'] . "[$client_id] said to You :" . $explode_array[1]));
  69. }
  70. // 群聊
  71. return GateWay::sendToAll(TextProtocol::encode($_SESSION['name'] . "[$client_id] said :" . $message));
  72. }
  73. }