服务端代码:
<?php
$clientFds = array();
//创建websocket服务器对象,监听0.0.0.0:9501端口
$ws = new swoole_websocket_server("0.0.0.0", 9501);
$ws->set(
array(
'worker_num' => 1,
)
);
//打开websocket连接事件
$ws->on('open', function(swoole_websocket_server $server, $request) use (&$clientFds) {
echo "新用户 $request->fd 登录 . \n";
$clientFds[] = $request->fd;
//var_dump($clientFds);
});
//监听websocket消息事件
$ws->on('message', function(swoole_websocket_server $server, $request) use (&$clientFds) {
foreach ($clientFds as $fd) {
# code...
$server->push($fd, $request->data);
}
});
//关闭连接事件
$ws->on('close', function(swoole_websocket_server $server, $fd) use (&$clientFds) {
echo "用户 {$fd} 下线. \n";
$key = array_search($fd, $clientFds);
unset($clientFds[$key]);
});
$ws->start();
客户端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket聊天室</title>
</head>
<body>
聊天窗口:
<div id="main" style="width:600px;height: 300px; overflow: auto;border: solid 2px black;">
</div>
<textarea id="textarea" placeholder="在这里输入信息"></textarea>
<br />
<input type="button" value="发送聊天" onclick="send()">
</body>
</html>
<script type="text/javascript">
var myDate = new Date();
var name = prompt("请输入您的昵称", "");
var main = document.getElementById("main");
var wsServer = 'ws://192.168.0.131:9501';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("连接成功.");
};
websocket.onclose = function (evt) {
console.log("连接已关闭...");
};
websocket.onmessage = function (evt) {
var data = evt.data;
console.log("收到 socket server 消息,内容:" + data);
main.innerHTML += data + "<br />";
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
function send() {
var data = document.getElementById("textarea").value;
if (data === "") {
alert("不能发送空信息");
return false;
}
websocket.send(name + ":" + data);
document.getElementById("textarea").value = "";
}
</script>