设为首页 收藏本站
查看: 1202|回复: 0

[经验分享] 网页聊天室PHP

[复制链接]

尚未签到

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


DSC0002.gif


  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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-103514-1-1.html 上篇帖子: php计算出当天时间的起始点与结束的备忘 下篇帖子: PHP如何判断浏览器类型及浏览器语言
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表