服务端代码
ini_set('display_errors', 1);
error_reporting(E_ALL);
$ws = new swoole_websocket_server("0.0.0.0", 8080);
//监听WebSocket连接打开事件 客户端 onopen 触发此事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件 客户端 send() 方法触发此事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");//以 fd 为标识发给客户端 触发客户端 onmessage 事件
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
客户端代码
<input id='msg'>
<h1 οnclick='send()'>发送</h1>
<script>
var wsServer = 'ws://47.106.184.48:8080';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {//链接成功事件
console.log("Connected to WebSocket server.",'evt:'+evt);
};
websocket.onclose = function (evt) {//关闭链接事件
console.log("Disconnected",'evt:'+evt);
};
websocket.onmessage = function (evt) {//接收消息事件 服务端 push事件 触发此事件
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {//发生错误后的事件
console.log('Error occured: ' + evt.data);
};
console.log(websocket);
function send(){
let v = document.getElementById('msg').value;
websocket.send(v);//触发 服务端 message 事件
}
</script>
安装 swoole 扩展后
php youServerFile.php
聊天室功能,则是以 fd 群发消息就 ok