1.安装swoole扩展,可自己编译或pecel install swoole
2.修改php.ini 增加 extension = “swoole.so”
3.命令行运行 php websocket.php
4.修改websocket.html的连接ip,浏览器运行http://127.0.0.1/swoole/websocket.html
websocket服务端代码 websocket.php
<?php
$server = new swoole_websocket_server(“0.0.0.0”, 9502);//0.0.0.0表示广播消息; 9502是刚才前端页面中定好的通信端口
$server->on(‘open’, function (swoole_websocket_server $server, $request) {
echo “server: handshake success with fd{$request->fd}n”;//$request->fd 是客户端id
});
$server->on(‘message’, function (swoole_websocket_server $server, $frame) {
echo “receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}n”;
//$frame->fd 是客户端id,$frame->data是客户端发送的数据
//服务端向客户端发送数据是用 $server->push( ‘客户端id’ , ‘内容’)
$data = $frame->data;
foreach($server->connections as $fd){
$server->push($fd , $data);//循环广播
}
});
$server->on(‘close’, function ($ser, $fd) {
echo “client {$fd} closedn”;
});
$server->start();
客户端js代码 websocket.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Title</title>
<style type=”text/css”>
#danmu {
width: 40px;
height: 360px;
background-color: gray;
}
#send_box {
position: absolute;
top: 500px;
left: 100px;
}
</style>
</head>
<body>
<script type=”text/javascript”>
console.log(‘尝试websocket和swoole的配合’);
var ws = new WebSocket(“ws://192.168.3.212:9502”);//一定要以ws://开头 ,端口是否可用(试验中可以直接关闭防火墙centos7用 systemctl stop firewalld.service ;7以下的用service iptables stop )
ws.onopen = function () {
console.log(“握手成功”);
ws.send(‘hello world!!!’);//向php服务器发送数据
};
ws.onmessage = function (e) {
console.log(“message:” + e.data);
var text_obj = ‘{ “text”:”‘ + e.data + ‘” , “color”:”red” ,”size”:”1″,”position”:”0″,”isnew”:” “}’; //构造加上了innew属性的字符串danmu对象
console.log(text_obj);
var new_obj = eval(‘(‘ + text_obj + ‘)’); //转化为js对象
document.getElementById(‘danmu’).innerHTML += text_obj+”n”;
//$(‘#danmu’).danmu(“add_danmu”, new_obj); //向插件中添加该danmu对象
};
ws.onerror = function () {
console.log(“error”);
};
function send() {
console.log(document.getElementById(‘content’).value);
ws.send(document.getElementById(‘content’).value); //将input输入框中的文字发送给后端服务器,让后端服务器广播之
}
</script>
<div id=”danmu”></div>
<div id=”send_box”>
<input id=”content” type=”text”>
<input type=”submit” onclick=”send()”>
</div>
</body>
</html>
下载地址