最近用Swoole写了一个聊天室 http://www.azcity.cn
下面发下聊天室的代码
server.php
<?php
require_once("redisDb.php" ); //自己简单些的redis类
require_once("rndChinaName.php" ); //用于随机生成名字
class server{
private $redis;
private $randName;
public function __construct(){
$this->redis = new redisDb();
$this->randName = new rndChinaName();
$this->redis->flushAll();
echo "redis is connect";
}
public function getChar($num) // $num为生成汉字的数量
{
$b = '';
for ($i=0; $i<$num; $i++) {
// 使用chr()函数拼接双字节汉字,前一个chr()为高位字节,后一个为低位字节
$a = chr(mt_rand(0xB0,0xD0)).chr(mt_rand(0xA1, 0xF0));
// 转码
$b .= iconv('GB2312', 'UTF-8', $a);
}
return $b;
}
public function getName(){
return $this->randName->getName();
}
public function socket(){
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
$ws->set([
// 'socket_buffer_size' => 128 * 1024 *1024, //必须为数字
'worker_num' => 2,
'task_worker_num' =>4,
]);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
$room = "xyf";
$name = $this->getName();
$this->redis->hset($room,$request->fd,$name);
$Pnum = $this->redis->hlen($room);
$json = array('type'=>'3','message'=>"欢迎 <span class='text-navy'>$name</span> 加入聊天室",'time'=>date('Y-m-d H:i:s',time()),'num'=>"在线人数:".$Pnum);
$str = json_encode($json);
foreach($ws->connections as $fd){
$ws->push($fd,$str);
}
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "message:{$frame->data}";
$task_id = $ws->task($frame);
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
$name = $this->redis->hget("xyf",$fd);
$this->redis->hdel("xyf",$fd);
$Pnum = $this->redis->hlen("xyf");
$json = array('type'=>'3','message'=>"<span class='text-navy'>$name</span> 离开聊天室",'time'=>date('Y-m-d H:i:s',time()),'num'=>"在线人数:".$Pnum);
$str = json_encode($json);
foreach($ws->connections as $fd1){
if($fd1 != $fd){
$ws->push($fd1,$str);
}
}
echo "client-{$fd} is closed\n";
});
$ws->on('Receive', function(swoole_server $ws, $fd, $from_id, $data) {
echo "接收数据" . $data . "\n";
$data = trim($data);
$task_id = $ws->task($data, 0);
$ws->send($fd, "分发任务,任务id为$task_id\n");
});
$ws->on('Task', function (swoole_server $ws, $task_id, $from_id,$frame) {
echo "Tasker进程接收到数据";
foreach($ws->connections as $fd){
echo "task_id:".$task_id."\n";
$num = $frame->fd%10;
$data = htmlspecialchars($frame->data);
$name = $this->redis->hget("xyf",$frame->fd);
if($fd==$frame->fd){
$json = array('name'=>"$name",'message'=>"$data",'time'=>date('Y-m-d H:i:s',time()),'type'=>'1','img'=>$num);
}else{
$json = array('name'=>"$name",'message'=>"$data",'time'=>date('Y-m-d H:i:s',time()),'type'=>'2','namet'=>"中文",'img'=>$num);
}
$str = json_encode($json,JSON_UNESCAPED_UNICODE);
$ws->push($fd,$str);
}
$ws->finish($data);
});
$ws->on('Finish', function (swoole_server $ws, $task_id, $data) {
echo "Task#$task_id finished, data_len=".strlen($data).PHP_EOL."\n";
});
$ws->start();
}
}
$wser = new server();
$wser->socket();
?>
index.html 客户端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP聊天室</title>
<meta name="keywords" content="PHP聊天室">
<meta name="description" content="PHP聊天室">
<link rel="shortcut icon" href="favicon.ico"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">
<link href="css/plugins/jsTree/style.min.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!--?v=4.1.0 -->
<style>
.wrapper-content{
padding:0px;
}
.ibox{
margin-bottom: 0px;
}
.ibox-title{
height:10vh;
}
.chat-discussion{
min-height:74vh;
}
.chat-message-form{
height:14vh;
}
#message{
height:14vh;
}
.alert{
padding:4px 8px;
text-align:center;
width:auto;
font-size: 4px;
border-radius:10px;
}
.come{
padding:5px;
margin-bottom:5px;
}
</style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox chat-view">
<div class="ibox-title">
<center><h4 class="text-navy">PHP-Swoole聊天室<span class="pull-right label label-primary" id="num"></span></h4></center>
</div>
<div class="ibox-content">
<div class="row">
<div cass="col-md-12">
<div class="chat-discussion">
</div>
</div>
<div class="col-sm-12">
<div class="chat-message-form">
<textarea class="form-control" name="message" id="message" placeholder="输入消息内容,按回车键发送"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<script src="js/message.js?v=1.0.5"></script>
<!-- 自定义js -->
</body>
</html>
message.js 客户端websocket的连接
if(window.WebSocket){
var webSocket = new WebSocket("ws://服务端IP:端口号");
webSocket.onopen = function (event) {
};
webSocket.onmessage = function (event) {
// console.log(event.data);
var data = JSON.parse(event.data);
// console.log(event.data);
var message = "";
if(data.type==3){
$('#num').html(data.num);
message += '<center><p class="come"><span class="alert alert-success">'+data.message+'</span></p></center>';
}else{
if(data.type==1){
message += '<div class="chat-message">';
}else{
message += '<div class="chat-message1">';
}
message += '<img class="message-avatar" src="img/a'+data.img+'.jpg" alt="">';
message += '<div class="message">'
message += '<span class="message-author">'+data.name+'</span>';
message += '<span class="message-date">'+data.time+'</span>';
message += '<span class="message-content">'+data.message+'</span>';
message += '</div>';
message += '</div>';
}
$('.chat-discussion').append(message);
$(".chat-discussion").scrollTop($(".chat-discussion")[0].scrollHeight);
};
var sendMessage = function(){
var message = $('#message').val();
if($.trim(message)==""){
$('#message').val("");
return false;
}else{
webSocket.send(message);
$('#message').val("");
}
}
}else{
console.log("您的浏览器不支持WebSocket");
}
$(document).keyup(function(event){
if(event.keyCode ==13){
sendMessage();
}
});
以上是主要的代码内容,若有什么疑问可以在下面留言,需要完整代码也可以在下面留言联系我