杨叔叔 发表于 2015-8-24 13:02:56

网页聊天室PHP

  毕业工作也一年多了,技术也有了些许提高。但是技术海洋是宽广的,我想从今天开始记录自己在工作学习中收获,与大家一起分享。好了,废话不多说,这是前几天帮别人写的一个网页聊天室。这种东西呢,网上也有很多源码,应该算写烂的东西了,当然我有一套自己的实现,很简单,如果要考虑效率,大家自行优化。
  先上数据库:
  第一个表是登录表,id自增长,因为聊天室是随机匹配的,也不用登录,所以每个进来的人都插入行,然后把把这个id作为该用户的标志
  to字段代表用户和谁匹配聊天,是匹配到用户的id
  time是最后一次通信的时间,如果30秒时间内没有任何通信信息,则认为掉线
  status是状态,0为初始状态,匹配到用户后变为1,掉线变为3

  第二个表,用于记录聊天信息的
  

  通信方面的话,采用的是最简单的ajax轮训。现在有各种技术,长连接之类的,不过我这个要求不高,所以没考虑。当然要很好的体验,我觉得还是要用flash做,或者html5。毕竟聊天这种东西是你来我往的,用socket非常方便,http的话很蛋疼,浪费服务器资源还体验不怎么好。
  然后是前端js代码:



1 $(document).ready(function(){
2   var url = "chatServer.php"+location.search;
3   var status = "0";
4   var msg = "";
5   var timer;
6   var delay = 5000;
7   run();
8   
9   function run() {
10       if(timer) {
11         clearTimeout(timer);
12       }
13       switch(status) {
14         case "0":
15               $("#showView").html("正在连接服务器...<br>");
16               login();
17               break;
18         case "1":
19               $("#showView").html("正在匹配好友...<br>");
20               match();
21               break;
22         case "2":
23               $("#showView").html("已匹配到好友,可以进行聊天...<br>");
24               chat();
25               break;
26         case "3":
27               chat();
28               break;
29         default:
30               status = "0";
31       }
32       timer = setTimeout(run,delay);
33   }
34   
35   function login() {
36       $.ajax({
37         url:url,
38         data:"type=login",
39             method:"POST",
40             success:function(data){
41               var objData = eval('(' + data + ')');
42               status = objData.status;
43             }
44       });
45   }
46   
47   function match(){
48       $.ajax({
49         url:url,
50         data:"type=match",
51             method:"POST",
52             success:function(data){
53               var objData = eval('(' + data + ')');
54               status = objData.status;
55             }
56       });
57   }
58   
59   function chat(){
60       var send = "type=msg";
61       if(msg!="") {
62         send += "&data="+msg;
63       }
64       msg = "";
65       $.ajax({
66         url:url,
67         data:send,
68             method:"POST",
69             success:function(data){
70               var objData = eval('(' + data + ')');
71               status = objData.status;
72               for(var i=0;i<objData.msg.length;i++) {
73                     var htmlMsg = $("<span> </span> ");
74                     if(objData.msg.user=="other") {
75                     htmlMsg.attr('style','color:blue');
76                     }
77                     htmlMsg.append(objData.msg.name+"&nbsp;&nbsp;"+getLocalTime(objData.msg.time) + "<br>&nbsp;&nbsp;&nbsp");
78                   var msg = $("<span></span>");
79                   msg.text(objData.msg.msg);
80                      htmlMsg.append(msg);
81                  htmlMsg.append('<br>');
82                  $("#showView").append(htmlMsg);
83               }
84             }
85       });
86   }
87   
88   function getLocalTime(nS) {   
89      var date = new Date(nS*1000);
90      return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
91   }
92   
93   $("#sendClick").bind('click',function(){
94       msg = $("#sendMsg").val();
95       $("#sendMsg").val("");
96       run();
97       return false;
98   });
99 });
  后端代码:





1 <?php
2 !defined('IN_COWFRAME') && exit('Access Denied');
3
4 class control extends index
5 {
6   private $ip;
7   public $time;
8   private $ownId;
9   private $toId=0;
10   function index(){
11         $this->time = time();
12         $this->_getUserDate();
13         
14         if($_POST['type']) {
15             $this->_dealRequest($_POST['type']);
16         }
17         else {
18             $this->_responseError();
19         }
20   }
21   
22   private function _dealRequest($type) {
23         switch ($type) {
24             case 'login':
25               $this->_login();
26               if($toId = $this->_chooseChatUser()) {
27                     $this->_responseInfo('chat');
28               }
29               else {
30                     $this->_responseInfo('login');
31               }
32               break;
33             case 'match':
34               if($this->toId) {
35                     $this->_responseInfo('chat');
36               }
37               else {
38                     if($this->_chooseChatUser()) {
39                         $this->_responseInfo('chat');
40                     }
41                     else {
42                         $this->_responseInfo('login');
43                     }
44               }
45               break;
46             case 'msg':
47               if($this->toId) {
48                     $this->_responseInfo('msg',$this->_chat());
49               }
50               else {
51                     $this->_responseInfo('login');
52               }
53         }
54   }
55   
56   private function _getUserDate() {
57         if(isset($_SESSION['userId'])) {
58             $this->ownId = $_SESSION['userId'];
59             $sql = "select * from chat_online where id = $this->ownId";
60             $data = $this->db->_query($sql)->fetch_one();
61             if(!$data) {
62               $this->_responseError();
63             }
64             if($data['status'] == 3) {
65               unset($_SESSION['userID']);
66               $_POST['type'] = "login" ;
67               return;
68             }
69             $this->toId = $data['to'];
70             $sql = "update chat_online set time = $this->time where id = $this->ownId";
71             $this->db->query($sql);
72         }
73         else {
74             if(!isset($_POST['type']) || $_POST['type']!="login") {
75               $this->_responseError();
76             }
77            
78         }
79         $sql = "update chat_onlie set status = 3 where time < ".($this->time-30);
80         $this->db->query($sql);
81   }
82   
83   private    function _login(){
84         $ip = $_SERVER['REMOTE_ADDR'];
85         $sql = "insert into chat_online(ip,time) values('$ip',$this->time)";
86         $this->db->query($sql);
87         $this->ownId = $this->db->_query("select LAST_INSERT_ID() as id")->fetch_one()['id'];
88         if(isset($_SESSION['userId'])) {
89             $sql = "update chat_online set status = 3 where id = {$_SESSION['userId']} ";
90             $this->db->query($sql);
91             $sql = "update chat_online set `to`=0 where `to` = {$_SESSION['userId']} ";
92             $this->db->query($sql);
93         }
94         $_SESSION['userId'] = $this->ownId;   
95   }
96   
97   private function _chooseChatUser() {
98         $sql = "select * from chat_online where status = 0 and id!=$this->ownId order by time limit 1 ";
99         $value = $this->db->_query($sql)->fetch_one();
100         if(isset($value['id'])) {
101             $this->toId = $value['id'];
102             $sql = "update chat_online set `status` = 1,`to`=$this->ownId where id = $this->toId ";
103             $this->db->query($sql);
104             $sql = "update chat_online set `status` = 1,`to`=$this->toId where id = $this->ownId ";
105             $this->db->query($sql);
106             return $this->toId ;
107         }
108         else {
109             return 0;
110         }
111   }
112   
113   private function _chat(){
114         $name = isset($_GET['username'])?$_GET['username']:'无名';// var_dump($_GET);
115         if(isset($_POST['data'])) {
116             $msg = $_POST['data'];
117             $sql = "insert into chat_event(userId,time,content,status,name)values($this->ownId,$this->time,'$msg',0,'$name') ";
118             $this->db->query($sql);
119         }
120         $sql = "select time,content,name from chat_event where status=0 and userId = $this->toId order by time ";
121         $data = $this->db->fetch_all($sql);
122         $sql = "update chat_event set status=1 where userId = $this->toId";
123         $this->db->query($sql);
124         $ret = array();
125         foreach($data as $one) {
126             $ret[] = array(
127               'user' => 'other',
128               'time'=>$one['time'],
129               'msg' => $one['content'],
130               'name' => $one['name'],
131             );
132         }
133         if(isset($msg)){
134             $ret[] = array('user'=>'own','time'=>$this->time,'msg'=>$msg,'name'=>$name);
135         }
136         return $ret;
137   }
138   
139   private function _responseError(){
140         echo json_encode(array('status'=>'error'));
141         exit();
142   }
143   
144   private function _responseInfo($type,$msg=null) {
145
146         switch ($type) {
147             case 'login':
148               echo json_encode(array('status'=>'1'));
149               break;
150             case 'chat':
151               echo json_encode(array('status'=>'2'));
152               break;
153             case 'msg':
154               $data = array('status'=>'3','msg'=>$msg);
155               echo json_encode($data);
156               break;
157         }
158         exit();
159   }
160 }
161
162
163 ?>
View Code  php代码用的是框架,当然这应该不太影响,只是用了db那块。我也比较懒,没有写好注释,优化代码,注意编程规范等。主要平时也是有时间就看书,没有时间处理这些了。我会在以后的帖子中注意这些编程规范
页: [1]
查看完整版本: 网页聊天室PHP