chat.php内容如下
<?php
//使用workerman,只需引入这个文件
require_once "workerman-4.0/Autoloader.php";
//创建服务器,监听3000端口
$wsServer=new \Workerman\Worker("websocket://127.0.0.1:3000");
$wsServer->onConnect=function ($conn){//$conn保存了当前用户的连接
//心跳,每隔2秒,发送消息
\Workerman\Lib\Timer::add(2,function () use($conn){
$conn->send(json_encode(array(['type'=>'ping','content'=>'心跳'])));
});
};
$wsServer->onMessage=function ($conn,$data){
// echo $data.PHP_EOL;
// $conn->send("我知道了");
//$conn->worker->connections 是一个数组,保存了所有客户端连接
foreach ($conn->worker->connections as $v){
if($v!=$conn){//自己写的消息不再发给自己
$v->send(json_encode(array(['type'=>'msg','content'=>$data])));//群聊,向所有连接的客户端发消息
}
}
};
$wsServer->onError=function (){
};
$wsServer->onClose=function (){
};
//让服务器开始运行
$wsServer->runAll();
用cmd启动服务
客户端代码,用的浏览器h5
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>首页</title>
<!-- <script src="/static/js/jquery.min.js"></script>-->
<script src="/static/js/jquery-1.12.3.js"></script>
<script src="/static/js/vue2_dev.js" type="text/javascript"></script>
<link href="/static/css/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="app" >
<button onclick="openJSSocket()" >js --- openJSSocket连接到服务器</button>
<div>
<div id="msbox" style="width: 600px;background: #fff;height: 300px;overflow: auto;border: 1px solid #000000">
</div>
<div>
<input type="text" id="msg" >
<button onclick="sendMesg()">发送</button>
</div>
</div>
</div>
<script>
var socket=null;
function openJSSocket(){
// 创建一个WebSocket对象
socket = new WebSocket("ws://127.0.0.1:3000");
// 当WebSocket连接成功时触发
socket.onopen = function(event) {
console.log("WebSocket 连接成功");
// 向服务器发送消息
socket.send("Hello Server!");
};
// 当收到服务器发送的消息时触发
socket.onmessage = function(event) {
console.log("收到服务器的消息:" + event.data);
//解析返回的json对象
var res=JSON.parse(event.data)
if(res[0].type=='msg'){
$("#msbox").append('<div class="serveclss">'+res[0].content+'</div>')
}
//直接显示数据
// $("#msbox").append('<div class="serveclss">'+event.data+'</div>')
};
// 当WebSocket连接关闭时触发
socket.onclose = function(event) {
console.log("WebSocket 连接关闭");
};
// 当发生错误时触发
socket.onerror = function(error) {
console.log("WebSocket 错误:" + error);
};
}
function sendMesg(){
var msg=$("#msg").val();
$("#msbox").append('<div class="myclss">'+msg+'</div>')
//发送信息到服务器
socket.send(msg)
}
</script>
<style>
.myclss{
background: #000088;
text-align: right;
color: #fff;
}
.serveclss{
background: #660066;
text-align: left;
color: #fff;
}
</style>
</body>
</html>