前端html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="display: block" id="data1">
<input type="text" id="a">
<button type="button" onclick="datas()">设置姓名</button>
</div>
<div style="display: none" id="data2">
<input type="text" id="img">
<button type="button" onclick="datas1()">发送信息</button>
</div>
<div style="display: none">
<input type="text">
</div>
<div style="display:block">
<div id="b"></div>
</div>
</body>
</html>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script>
<script>
var wsServer = 'ws://121.4.89.71:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("已连接")
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log("已发送")
console.log(evt.data);
$("#b").append("<div>"+evt.data+"</div>")
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
function datas() {
var name=$("#a").val();
if (name=!""){
$("#data1").prop("style","display:none");
$("#data2").prop("style","display:block");
}
}
function datas1() {
var datad="name"+":"+$("#a").val()+","+"img"+":"+$("#img").val();
// console.log(data);
websocket.send(datad);
}
</script>
php代码
<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
// 设置当前客户端id和默认的匿名用户
$GLOBALS['fd'][$request->fd]['id']=$request->fd;
$GLOBALS['fd'][$request->fd]['name']="客服";
// print_r($GLOBALS['fd']);
});
//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
$data=$frame->data;
$array=explode(",",$data);
$name=explode(":",$array[0]);
$img=explode(":",$array[1]);
$info[$name[0]]=$name[1];
$info[$img[0]]=$img[1];
if(!empty($info["name"])){
$GLOBALS['fd'][$frame->fd]['name']=$info["name"];
}
// print_r($GLOBALS[fd]);
// 拼接返回的值
$data= $GLOBALS['fd'][$frame->fd]['name'].":".$info['img'];
// 给各个客户端赋值
foreach ($GLOBALS['fd'] as $i){
$ws->push($i['id'], "$data");
}
// print_r($info);
});
//监听WebSocket连接关闭事件
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
?>