Chat.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. ini_set('display_errors', 'on');
  3. error_reporting(E_ALL);
  4. $ip = isset($argv[1]) ? $argv[1] : '127.0.0.1';
  5. $port = isset($argv[2]) ? $argv[2] : 8480;
  6. $sock = stream_socket_client("tcp://$ip:$port");
  7. if(!$sock)exit("can not create sock\n");
  8. fwrite($sock, 'connect');
  9. $rsp_string = fgets($sock, 1024);
  10. $ret = json_decode($rsp_string, true);
  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 = fgets($fd, 102400);
  37. if(!$ret){continue;exit("connection closed\n ");}
  38. // 是服务端发来的心跳,只是检测联通性,不用回复
  39. if("#ping#" == $ret)
  40. {
  41. continue;
  42. }
  43. $ret = json_decode(trim($ret),true);
  44. if($ret['to_uid'] == $MYUID)
  45. {
  46. echo $ret['from_uid'] , ' say to YOU:', $ret['message'], "\n";
  47. }
  48. else
  49. {
  50. echo $ret['from_uid'] , ' say to ALL:', $ret['message'], "\n";
  51. }
  52. continue;
  53. }
  54. // 向某个uid发送消息 格式为 uid:xxxxxxxx
  55. $ret = fgets(STDIN, 10240);
  56. if(!$ret)continue;
  57. if(preg_match("/(\d+):(.*)/", $ret, $match))
  58. {
  59. $uid = $match[1];
  60. $words = $match[2];
  61. fwrite($sock, json_encode(array('from_uid'=>$MYUID, 'to_uid'=>$uid, 'message'=>$words))."\n");
  62. continue;
  63. }
  64. // 向所有用户发消息
  65. fwrite($sock, json_encode(array('from_uid'=>$MYUID, 'to_uid'=>'all', 'message'=>$ret))."\n");
  66. continue;
  67. }
  68. }
  69. }