这几天抽空学习了下swoole, 真的很强大, 很好用. 官方wikihttps://wiki.swoole.com/wiki/
这是我仿照文档写的一个简单页面, 可以实现在线聊天: http://62.234.72.223:8080/
我的运行环境是: php7.3 + swoole4.2.12
服务器代码: ws_server.php
<?php
//创建websocket服务器对象, 监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
$ws->set([
'daemonize' => 1, //作为守护进程运行
]);
$client_list = new swoole_table(1024);
$client_list->column('fd', swoole_table::TYPE_STRING, 64);
$client_list->create();
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) use ($client_list) {
echo "client-" . $request->fd . " is connect\n";
$ws->push($request->fd, data_pack($request->fd, "连接成功!\n"));
// swoole_timer_tick(200, function ($timer_id) use ($ws, $request) {
// $ws->push($request->fd, "hello, welcome\n");
// });
//绑定uid
// $ws->bind($request->fd, 1);
$client_list->set($request->fd, ['fd' => $request->fd]);
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) use ($client_list) {
foreach ($client_list as $row) {
$ws->push($row['fd'], data_pack($frame->fd, $frame->data));
}
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) use ($client_list) {
$client_list->del($fd);
echo "client-" . $fd . " is closed\n";
});
$ws->start();
//json格式化数据
function data_pack($fd, $data) {
return json_encode([
'uid' => $fd,
'data' => $data,
'time' => date('Y-m-d H:i:s'),
]);
}
前端代码: index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>websocket聊天</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="col-md-8 col-md-offset-1">
<table id="chat_wrapper" class="table table-hover">
<tr>
<th>uid</th>
<th>内容</th>
<th>时间</th>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<input id="send_data" type="text" class="form-control" placeholder="Text input">
</div>
<div class="col-md-2">
<button id="send" type="button" class="btn btn-primary">发送</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
// var wsServer = "ws://127.0.0.1:9502";
var wsServer = "ws://62.234.72.223:9502"; //设置自己的
var websocket = new WebSocket(wsServer);
var chat_str = '';
websocket.open = 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);
var chat_row = JSON.parse(evt.data);
chat_str = '<tr><td>' + chat_row.uid + '</td><td>' + chat_row.data + '</td><td>' + chat_row.time + '</td></tr>';
$("#chat_wrapper").append(chat_str);
};
websocket.onerror = function (evt) {
console.log("Error occured: " + evt.data);
};
$("#send").click(function () {
websocket.send($("#send_data").val());
});
</script>
</html>
运行: php ws_server.php 就可以在页面中在线聊天啦~