下载安装完swoole,开启websocket服务器
php ws_server.php
服务端code
class WebSocketTest
{
public $server;
public function __construct()
{
$this->server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$this->server->on('open', function (Swoole\WebSocket\Server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";
});
$this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
foreach ($this->server->connections as $fd) {
$server->push($fd, $frame->data);
}
});
$this->server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$this->server->on('request', function ($request, $response) {
// 接收http请求从get获取message参数的值,给用户推送
// $this->server->connections 遍历所有websocket连接用户的fd,给所有用户推送
foreach ($this->server->connections as $fd) {
// 需要先判断是否是正确的websocket连接,否则有可能会push失败
if ($this->server->isEstablished($fd)) {
$this->server->push($fd, $request->get['message']);
}
}
});
$this->server->start();
}
}
new WebSocketTest();
浏览器客户端code
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试聊天</title>
<style>
#chart {
width: 300px;
height: 500PX;
border: 1px solid black;
}
</style>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<p>鲁ICP备18023280号</p>
<div id="chart"></div>
<div class="content">
<div class="section"></div>
<form action="#">
<input type="text" id="val">
<button type="button" id="sub">发送</button>
</form>
</div>
<script>
$('#sub').click(function () {
var val = $('#val').val();
websocket.send(val);
})
var wsServer = 'ws://140.143.12.166:9501';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
//console.log('Retrieved data from server: ' + evt.data);
push(evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
function push(data) {
html = '<div>';
html += data;
html += '</div>';
$("#chart").append(html);
}
</script>
</body>
</html>