├── README.md ├── database.json ├── server.php └── index.html /README.md: -------------------------------------------------------------------------------- 1 | # xchat 2 | A simple chat room based on Ajax long polling 3 | -------------------------------------------------------------------------------- /database.json: -------------------------------------------------------------------------------- 1 | [{"time":"1595939294719","name":"TEST","input":"\u6d4b\u8bd5"}] -------------------------------------------------------------------------------- /server.php: -------------------------------------------------------------------------------- 1 | read('database.json'); 14 | if(empty($arr)) 15 | { 16 | $arr = array(); 17 | } 18 | // 获取原来的数据库 19 | $num = count($arr); 20 | if($num >= MAX) 21 | { 22 | //设置最大保存信息个数,防止boom 23 | unset($arr[0]); //删除第一个(最老的) 24 | $arr[$num] = array( 25 | 'time' => $time, 26 | 'name' => $name, 27 | 'input' => $input 28 | ); 29 | $arr = array_values ($arr);//重新建立索引 30 | } else { 31 | $arr[$num] = array( 32 | 'time' => $time, 33 | 'name' => $name, 34 | 'input' => $input 35 | ); 36 | } 37 | $data = json_encode($arr); 38 | $f ->write('database.json',$data); 39 | echo '200'; 40 | break; 41 | case 'GET': 42 | while(true){ 43 | $f = new file(); 44 | $arr = $f -> read('database.json'); 45 | $j = 0; 46 | $NEW = array(); 47 | if(empty($arr)) 48 | { 49 | $arr = array(); //初始话 50 | } 51 | for($i = 0;$i <= count($arr) -1;$i++) 52 | { 53 | if((double)$arr[$i]['time'] >= (double)$time) 54 | { 55 | $NEW[$j] = $arr[$i]; 56 | $timex = substr($arr[$i]['time'],0,-3); //时间戳转换为时间 57 | $NEW[$j]['time'] = date("m/d H:i:s",$timex); 58 | $j++; 59 | } 60 | } 61 | // 获取原来的数据库遍历查询新消息 62 | if(!empty($NEW[0])) 63 | { 64 | echo json_encode($NEW); 65 | break; 66 | } 67 | usleep(SLEEP); 68 | } 69 | break; 70 | } 71 | 72 | class file { 73 | function write($filepath,$content) { 74 | file_put_contents($filepath, $content); 75 | } 76 | function read($filepath) { 77 | if (file_exists($filepath)) { 78 | $str = file_get_contents($filepath); 79 | return json_decode($str,true); 80 | } else { 81 | self::write($filepath,''); 82 | } 83 | } 84 | } 85 | ?> -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | XCHAT 8 | 9 | 10 |
11 | 12 |
13 | 用户名和信息不能为空 14 |
15 | 16 |
17 |

18 |       
91 |     
92 | 
93 | 


--------------------------------------------------------------------------------