做了一个php swoole websocket+redis 的即时聊天室功能,qq第三方登录

时间 17 : 24 , Apr 26,2018

先试qq第三方登录后,可以发给全部用户或者单个用户,用户数据保存在redis,聊天数据保存在redis的list里,然后可以消息队列放入数据库。

演示地址:http://lxclog.cn/client.php

github库:https://github.com/jipq1016/chatroom

websocket.php。

代码如下:

class webSocket{    
private $redis=null;    
private $ws=null;    
private $is_all=null;    
//构造函数    
function __construct(){    
 	$this->redis=new Redis();    
        $this->ws=new swoole_websocket_server('0.0.0.0',9500);	            
	 //连接服务
	 $this->redis->connect('127.0.0.1','6379',1);
	 $this->ws->on('open',function($ws,$res){
		   // var_dump($res);
         
	 });
	 //监听websocket消息事件
	 $this->ws->on('message',function($ws,$job){
              //var_dump($job);
		    $json=$job->data;
		    $data=json_decode($json,1);
		    /*登录部分开始*/
		    if(@$data['login']==1){ 
               $this->openid=$data['qq_openid'];
		      if(!empty($this->openid)){
		       $status=$this->redis->zscore("user_list",$this->openid);;//获取在线用户表
			  //判断此用户当前端口是否还在使用
			  $check="";
			  foreach ($this->ws->connections as $fd) {
					if($fd==$status){
					 $check=1;
					}
                 }
			   if($status==true && $check==1){
				//关闭重复登录客户端	
                    echo "重复登录!";
			     $msg=array("close"=>1,"msg"=>"您已经在别地登录!");
				$json=json_encode($msg);
				$this->send(0,$job->fd,$json);
                    exit;
			   }else{
			   //redis记录用户信息,除了qq_openid,其他参数都会变
				 $arr=array(
                         "fd"=>$job->fd,
					"name"=>$data['user_info']['nickname'],
				     "figureurl"=>$data['user_info']['figureurl'],
					"time"=>date("Y-m-d H:i:s",time()),
					"json"=>$json
			      );
			   $this->redis->hmset($this->openid,$arr); //记录用户信息
                  //登录成功后先记录到在线用户set集合user_list,然后获取在线用户信息列表
                  $this->redis->zAdd('user_list',$job->fd,$this->openid);
			   $user_list_json=$this->json_user_list();
			   $this->send(1,0,$user_list_json); //将在线用户列表发给所有人
			   }
 
			  }
		    
		    }
		    /*聊天部分开始*/
		    if(!empty($data['to_fd'])){
				  $to_fd=$data['to_fd']; //给谁
				  $msg=$data['msg'];     //内容
				  $fromfd= $job->fd;
			 	  
   			   if($to_fd=="all"){
			       $is_all=1;
			    }
		      $msg_arr['type']="msg";
                @$msg_arr['is_all']=$is_all?:0;
			 $msg_arr['from']=$fromfd;
			 $msg_arr['msg']=$msg;
			 $msg_arr['time']=date("Y-m-d H:i:s");
			 $msg_json=json_encode($msg_arr);
			 //保存到redis的list里缓存
			 $from_openid=$this->redis->zrangebyscore('user_list',$job->fd,$job->fd);
			 if($to_fd!="all"){
			 $to_openid=$this->redis->zrangebyscore('user_list',$to_fd,$to_fd);
			 $to_openid=$to_openid[0];
			 }else{
			  $to_openid='all';
			 }
		     	$redis_list['from']=$from_openid[0];
				$redis_list['to']=$to_openid;
				$redis_list['msg']=$msg;
				$redis_list['datetime']=$msg_arr['time'];
                $list_json=json_encode($redis_list);
                $this->redis->lpush('message_list',$list_json);
                $this->send(@$is_all,$to_fd,$msg_json);
		    }  
		  // echo "Message:{$job->data}\n";
	 });
   
	 //监听websocket链接关闭事件
	 $this->ws->on('close',function($ws,$fd){
       echo "client-{$fd} is closed\n";
       $close_user=$this->redis->zrangebyscore("user_list",$fd,$fd);
       //var_dump($close_user);
       $this->redis->zrem("user_list",$close_user[0]);//设置登录状态未登录	 
       	
       var_dump($close_user);
      //刷新好友列表
	 });
      $this->ws->start();
   }
 //给客户端发送数据
 private function send($is_all,$fd,$msg){
        if ($is_all) {  
            foreach ($this->ws->connections as $fd) {  
                $this->ws->push($fd, $msg);  
            }  
        } else {  
            $this->ws->push($fd, $msg);  
        }  
 }
 //获取所有在线用户信息
 private function json_user_list(){
        $user_list=$this->redis->zrangebyscore('user_list', 0, 10000000);
	   $list=array();
	   foreach($user_list as  $k=>$v){
		 $arr[$v]=$this->redis->hgetall($v);
	   }
	   $list['type']="user_list";
	   $list['user_list']=$arr;
	   return json_encode($list);
 }
}
$server=new webSocket;
?>


client.php

前端网页代码如下

<?php    
session_start();    
$_SESSION['swoole']='swoole';    
$qq_openid=$_SESSION['qqOpenid'];    
$qq_user=$_SESSION['qqUser'];    
if($_GET['clear']==1){  //清空qq登录记录    
	$_SESSION['qqOpenid']="";    
	$_SESSION['qqUser']="";    
$qq_openid="";    
	$qq_user="";    
}else{    
$user['login']=1;    
$user['qq_openid']=$qq_openid;    
$user['user_info']=$qq_user;    
}    
$qq_user_json=json_encode($user);    
?>    
<!DOCTYPE html>      
<html>      
<head>      
<meta charset="utf-8">      
<title>聊天室客户端</title>     
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>      
<script>    
var is_connect = false;    
var websocket = null;    
var is_log = false;    
var usr = '';    
var num= "";    
var qq_openid="<?php echo $qq_openid?>";    
function init(){    
var wsServer='ws://115.28.167.236:9500';    
websocket=new WebSocket(wsServer);    
websocket.onopen = function(evt){    
is_connect = true;    
console.log('connect!');    
var qq_user_json='<?php echo $qq_user_json?>';    
//post传qq用户信息    
//var fd=new FormData();    
//fd.append("type","post");    
//fd.append("data",qq_user_json);        
//var json=JSON.stringify(qq_user_json);    
websocket.send(qq_user_json);    
};    
websocket.onclose = function(evt){    
console.log('close!');    
};    
websocket.onmessage = function(evt){    
		console.log('from server:'+evt.data);    
var json_data = JSON.parse(evt.data);      
if(json_data.close==1){    
		alert(json_data.msg);    
		location.href="?clear=1";//清空保存的session    
		}     
		if(json_data.type=="user_list"){ //更新用户列表    
$(".member_list").html("<div onclick=select('all')>全部<span id='all_num'></span></div>");    
		user_list=new Array();    
		$.each(json_data.user_list,function(key,val){    
				var str="";    
				if(key==qq_openid){    
				str="style='display:none'";    
				}		        
		user_list[val.fd]='<img src='+val.figureurl+'>'+val.name;     
			$(".member_list").append("<div "+str+" onclick='select("+val.fd+")'><img src="+val.figureurl+">"+val.name+"<span id='num_"+val.fd+"' class='red'></span></div>");  	        
		})     
		}    
		if(json_data.type=="msg"){    
		fromfd=json_data.from;    
		msg=json_data.msg;    
			time=json_data.time;    
			console.log(user_list);    
		$.each(user_list,function(k,v){    
				if(v!="" || v!="undefined"){     
				if(k==fromfd){    
				userdata=v;    
				}    
				}    
			});    
			if(json_data.is_all=="1"){    
			str='<div class="all" style="display:none">'+userdata+'对大家说:'+msg+'<br>'+time+'</div>';    
			count=$('#all_num').html();    
			if(count==""){ count =0;}    
			$('#all_num').html(parseInt(count)+1);    
			}else{    
			str='<div class="f_'+fromfd+'" style="display:none">'+userdata+':'+msg+'<br>'+time+'</div>';    
			count=$('#num_'+fromfd).html();	    
			if(count==""){ count =0;}    
			$('#num_'+fromfd).html(parseInt(count)+1);//没有读取的用户信息    
			}	    
		$(".message_list").append(str);	    
			//当前对象    
			num=$('#num').val();    
		if(num=="all"){    
			$("div[class^='f_']").hide();	      
			$('.all').show();    
		}else{    
		$('.all').hide();    
			$("div[class^='f_']").hide();	      
			$('.f_'+num).show();    
		}    
$('.message_list')[0].scrollTop= $('.message_list')[0].scrollHeight;     
		}    
};    
websocket.onerror = function (evt,e){    
console.log('Error occured:'+ evt.data);    
};    
}    
//qq登录后才连接服务器    
<?php     
if($qq_openid){    
?>      
init();    
<?php    
}    
?>    
//选择发送对象    
function select(num){	      
if(num=="all"){    
//发给所有人	       
$('.who').html('全部');      
			$("div[class^='f_']").hide();	      
$('.all').show();    
$('#all_num').html("");    
}else{    
//发给指定的人    
$('.who').html(user_list[num]);		    
			$("div[class^='f_']").hide();	      
$('.all').hide();    
$('.f_'+num).show();    
$('#num_'+num).html("");    
}    
$('.message_list')[0].scrollTop= $('.message_list')[0].scrollHeight;     
$("#num").val(num);    
}    
//发送数据    
function get_message(){    
var send_msg=$.trim($('#message').val());    
num=$("#num").val();    
if(send_msg==""){ return  }    
if(num==""){    
num="all";    
}    
var data={'to_fd':num,'msg':send_msg};    
var json=JSON.stringify(data);    
websocket.send(json);    
if(num!='all'){    
$('.message_list').append('<div class="f_'+num+' right">对他说:'+send_msg+'</div>');    
}else{    
//$('.message_list').append('<div class="all">'+send_msg+'</div>');    
}    
$('.message_list').scrollTop = $('.message_list').scrollHeight;     
$("#message").val("");    
}    
function toLogin()    
{    
//以下为按钮点击事件的逻辑。注意这里要重新打开窗口    
//否则后面跳转到QQ登录,授权页面时会直接缩小当前浏览器的窗口,而不是打开新窗口    
/*var A=window.open("Connect2.1/qq_login.php","TencentLogin",     
 "width=450,height=320,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1");    
  */    
		location.href="Connect2.1/qq_login.php";    
			}     
			function closeQqWindow()    
{    
A.close();    
		}    
</script>    
<style>    
.message_list{overflow:scroll;width:700px;height:300px;border:1px solid #000000;margin:10px;margin-left:210px;}    
.member_list{overflow:scroll;float:left;width:200px;height:300px;border:1px solid #666666}    
.message{width:500px;height:50px;}    
.right{text-align:right};    
.who{width:100%;}    
#all_num{color:#ff0000}    
.red{color:#ff0000}    
</style>    
</head>    
<body>    
<div class="main">    
<div class="member_list">    
<span>用户列表</span>    
</div>    
<div class="message_list">    
<p class="who" align="center">全部</p>    
</div>    
</div>    
<br/><br/>    
<input class='message' type='text' id="message">    
<br/><br/>    
<input type="hidden" id="num" value="all">    
<?php    
if(empty($qq_openid)){    
?>    
<img src="http://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/bt_blue_76X24.png" onclick="toLogin()">    
&nbsp;&nbsp;    
<input type="button" value="提交" onclick="alert('qq登陆授权后,方可留言!');"/>    
<?php    
}else{    
?>    
<input type='button' onclick="get_message()" value="提交">    
<?php    
}    
?>    
</body>    
</html>

message_list.php

消息队列保存到本地数据库

connect("127.0.0.1","6379",1);
//连接数据库
$conn=mysqli_connect('127.0.0.1','jipq1016','Jipq_1016');
mysqli_select_db($conn,'myserver');
mysqli_query($conn,'set names "utf-8"');
while(1){
  if($redis->lsize('message_list')>0){	
  //取出队列最后一条数据,添加进数据库
  $last=$redis->rpop('message_list');
  $data=json_decode($last,1);
  $sql="insert into chatroom (`from`,`to`,`msg`,`datetime`) values ('".$data['from']."','".$data['to']."','".$data['msg']."','".$data['datetime']."')";
  $res=mysqli_query($conn,$sql);
  sleep(3);
  }else{
  sleep(3);
  }
}
?>


还有就是qq登录回调的页面里面,获取用户信息后,跳转到客户端页面!

if($_GET['code']){
require_once("Connect2.1/API/qqConnectAPI.php");
$qc = new QC();
$acs=$qc->qq_callback();
$openid=$qc->get_openid();
$qc2 = new QC($acs,$openid);
$qqUser = $qc2->get_user_info();
$_SESSION['qqOpenid']=$openid;
$_SESSION['qqUser']=$qqUser;
if($_SESSION[swoole]=='swoole'){
go_url('client.php');exit;
}


留 言

  

网站简介

作者的个人博客,记事本,记录工作和学习中遇到的问题和一些基础功能开发!
好好学习,天天向上!

常用网站

Copyright © 2016-2024 LXC.All rights reserved. 皖ICP备2023025580号-1