Chat.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. $ret = json_decode(trim($ret),true);
  39. if($ret['to_uid'] == $MYUID)
  40. {
  41. echo $ret['from_uid'] , ' say to YOU:', $ret['message'], "\n";
  42. }
  43. else
  44. {
  45. echo $ret['from_uid'] , ' say to ALL:', $ret['message'], "\n";
  46. }
  47. continue;
  48. }
  49. // 向某个uid发送消息 格式为 uid:xxxxxxxx
  50. $ret = fgets(STDIN, 10240);
  51. if(!$ret)continue;
  52. if(preg_match("/(\d+):(.*)/", $ret, $match))
  53. {
  54. $uid = $match[1];
  55. $words = $match[2];
  56. fwrite($sock, json_encode(array('from_uid'=>$MYUID, 'to_uid'=>$uid, 'message'=>$words))."\n");
  57. continue;
  58. }
  59. // 向所有用户发消息
  60. fwrite($sock, json_encode(array('from_uid'=>$MYUID, 'to_uid'=>'all', 'message'=>$ret))."\n");
  61. continue;
  62. }
  63. }
  64. }