Chat.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. require_once __DIR__ . '/../Protocols/JsonProtocol.php';
  3. ini_set('display_errors', 'on');
  4. error_reporting(E_ALL);
  5. $ip = isset($argv[1]) ? $argv[1] : '127.0.0.1';
  6. $port = isset($argv[2]) ? $argv[2] : 8480;
  7. $sock = stream_socket_client("tcp://$ip:$port");
  8. if(!$sock)exit("can not create sock\n");
  9. fwrite($sock, JsonProtocol::encode('connect'));
  10. $ret = read_data($sock);
  11. if(isset($ret['uid']))
  12. {
  13. echo "chart room login success , your uid is [{$ret['uid']}]\n";
  14. echo "use uid:words send message to one user\n";
  15. echo "use words send message to all\n";
  16. }
  17. else
  18. {
  19. exit("connet faild reponse:$rsp_string\n");
  20. }
  21. $MYUID = $ret['uid'];
  22. stream_set_blocking($sock, 0);
  23. stream_set_blocking(STDIN, 0);
  24. $read = array(STDIN, $sock);
  25. $write = $ex = array();
  26. while(1)
  27. {
  28. $read_copy = $read;
  29. if($ret = stream_select($read_copy, $write, $ex, 1000))
  30. {
  31. foreach($read as $fd)
  32. {
  33. // 接收消息
  34. if((int)$fd === (int)$sock)
  35. {
  36. $ret = read_data($fd);
  37. if(!$ret){continue;exit("connection closed\n ");}
  38. // 是服务端发来的心跳,只是检测联通性,不用回复
  39. if("#ping#" == $ret)
  40. {
  41. continue;
  42. }
  43. if($ret['to_uid'] == $MYUID)
  44. {
  45. echo $ret['from_uid'] , ' say to YOU:', $ret['message'], "\n";
  46. }
  47. else
  48. {
  49. echo $ret['from_uid'] , ' say to ALL:', $ret['message'], "\n";
  50. }
  51. continue;
  52. }
  53. // 向某个uid发送消息 格式为 uid:xxxxxxxx
  54. $ret = fgets(STDIN, 10240);
  55. if(!$ret)continue;
  56. if(preg_match("/(\d+):(.*)/", $ret, $match))
  57. {
  58. $uid = $match[1];
  59. $words = $match[2];
  60. fwrite($sock, JsonProtocol::encode(array('from_uid'=>$MYUID, 'to_uid'=>$uid, 'message'=>$words)));
  61. continue;
  62. }
  63. // 向所有用户发消息
  64. fwrite($sock, JsonProtocol::encode(array('from_uid'=>$MYUID, 'to_uid'=>'all', 'message'=>$ret)));
  65. continue;
  66. }
  67. }
  68. }
  69. function read_data($socket)
  70. {
  71. $buf = stream_socket_recvfrom($socket, 4);
  72. if($buf == '')
  73. {
  74. return;
  75. }
  76. $remain_len = JsonProtoCol::check($buf);
  77. //echo '$remain_len:'.$buf.':'.bin2hex($buf).":".$remain_len."\n";
  78. $buf .= stream_socket_recvfrom($socket, $remain_len);
  79. stream_set_blocking($socket, 0);
  80. //echo '$buf:'.$buf."\n";
  81. return JsonProtocol::decode($buf);
  82. }