Chat.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. $rsp_string = fgets($sock, 1024);
  11. $ret = JsonProtocol::decode($rsp_string);
  12. if(isset($ret['uid']))
  13. {
  14. echo "chart room login success , your uid is [{$ret['uid']}]\n";
  15. echo "use uid:words send message to one user\n";
  16. echo "use words send message to all\n";
  17. }
  18. else
  19. {
  20. exit("connet faild reponse:$rsp_string\n");
  21. }
  22. $MYUID = $ret['uid'];
  23. stream_set_blocking($sock, 0);
  24. stream_set_blocking(STDIN, 0);
  25. $read = array(STDIN, $sock);
  26. $write = $ex = array();
  27. while(1)
  28. {
  29. $read_copy = $read;
  30. if($ret = stream_select($read_copy, $write, $ex, 1000))
  31. {
  32. foreach($read as $fd)
  33. {
  34. // 接收消息
  35. if((int)$fd === (int)$sock)
  36. {
  37. $ret = fgets($fd, 102400);
  38. if(!$ret){continue;exit("connection closed\n ");}
  39. // 是服务端发来的心跳,只是检测联通性,不用回复
  40. if("#ping#" == $ret)
  41. {
  42. continue;
  43. }
  44. $ret = JsonProtocol::decode(trim($ret));
  45. if($ret['to_uid'] == $MYUID)
  46. {
  47. echo $ret['from_uid'] , ' say to YOU:', $ret['message'], "\n";
  48. }
  49. else
  50. {
  51. echo $ret['from_uid'] , ' say to ALL:', $ret['message'], "\n";
  52. }
  53. continue;
  54. }
  55. // 向某个uid发送消息 格式为 uid:xxxxxxxx
  56. $ret = fgets(STDIN, 10240);
  57. if(!$ret)continue;
  58. if(preg_match("/(\d+):(.*)/", $ret, $match))
  59. {
  60. $uid = $match[1];
  61. $words = $match[2];
  62. fwrite($sock, JsonProtocol::encode(array('from_uid'=>$MYUID, 'to_uid'=>$uid, 'message'=>$words)));
  63. continue;
  64. }
  65. // 向所有用户发消息
  66. fwrite($sock, JsonProtocol::encode(array('from_uid'=>$MYUID, 'to_uid'=>'all', 'message'=>$ret)));
  67. continue;
  68. }
  69. }
  70. }