websocket是什么及原理可以参考
https://www.jianshu.com/p/aa7235ddd74e
这里描述个基于swoole的websocket 匿名群聊
UI
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>即时通讯系统</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
</head>
<body>
<div id="convo">
登录用户id:<input type="text" name="user" >
<button class="login">登录</button>
<ul class="chat-thread">
</ul>
<!--聊天框-->
<div class="chat-window">
<input class="chat-window-message" name="chat-window-message" autocomplete="on" placeholder="请输入内容按回车键发送" type="text" value="123">
</div>
</div>
<!--引入jq文件-->
<script src='jquery.js'></script>
<script type="text/javascript">
$('.login').on('click' , function(){
uid = $('[name=user]').val().trim();
if(uid ==''){
alert('请先登录');
}else{
socketlogin(uid);
}
})
var socket;
function socketlogin(uid){
socket=new WebSocket('ws://103.60.221.52:9502?uid=' + uid);
socket.onopen=function()
{
socket.send(setMsg(1,'用户'+uid+"你好",uid));
console.log('连接成功');
}
socket.onmessage=function(e)
{
console.log('接收数据');
console.log(e);
$('.chat-thread').append('<li class="left">'+e.data+'</li>');
}
socket.onclose= function()
{
$('.chat-thread').append('<li class="left">退出聊天室</li>');
}
}
$(document).keydown(function(e){
if(e.keyCode==13){
var speak=$('.chat-window-message').val();
$('.chat-thread').append('<li>'+speak+'</li>');
$('.chat-window-message').val('');
socket.send(setMsg(2,speak,uid));
}})
function setMsg(type,msg , uid){
var msgObject = {
type:type,
msg: msg ,
uid: uid ,
}
return JSON.stringify(msgObject);
}
</script>
server.php
<?php
// 存储在线客户的数组
$userFdList = [];
$server = new swoole_websocket_server("0.0.0.0", 9502);
$server->on('open',function($server,$requset) use(&$userFdList){
//$userFdList[$request->get['uid']] = $request->fd ; 用于给特定人发送情况
$server->push($requset->fd,"欢迎来到同性交友群");
});
$server->on('message',function($server,$frame) use(&$userFdList){
$datas = json_decode($frame->data , true);
// var_dump($datas);
// var_dump($userFdList);
//匿名群聊
foreach($server->connection_list() as $key =>$val){
$server->push($val,"{$datas['msg']}");
}
// 特定人发送
// if($datas['type'] == 1){
// $server->push($userFdList[$datas['uid']], "系统:{$datas['msg']}");
// } else if( !isset($userFdList[$datas['to_uid']])) {
// $server->push($userFdList[$datas['uid']], "系统:用户没上线");
// } else {
// $server->push($userFdList[$datas['to_uid']], "别人(uid:{$datas['uid']}):{$datas['msg']}");
// }
// $server->push($frame->fd,{$frame->data});
});
$server->on('close', function($server, $fd) use (&$userFdList){
echo "connection close: {$fd}\n";
// 特定人发送
// foreach ($userFdList as $key => $value) {
// if( $value == $fd ) unset($userFdList[$key]);
// }
});
$server->start();
?>
用户123.png
用户7889.png
用户123接受到7889发的消息.png
网友评论