服务器端:socket.php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
$fd[] = $request->fd;
$GLOBALS['fd'][] = $fd;
//$ws->push($request->fd, "hello, welcome
");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
$msg = 'from'.$frame->fd.":{$frame->data}
";
//var_dump($GLOBALS['fd']);
//exit;
foreach($GLOBALS['fd'] as $aa){
foreach($aa as $i){
$ws->push($i,$msg);
}
}
// $ws->push($frame->fd, "server: {$frame->data}");
// $ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed
";
});
$ws->start();
客户端:Socket.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="发送数据" onclick="song()">
</body>
<script>
var msg = document.getElementById("msg");
var wsServer = 'ws://192.168.1.253:9502';
//调用websocket对象建立连接:
//参数:ws/wss(加密)://ip:port (字符串)
var websocket = new WebSocket(wsServer);
//onopen监听连接打开
websocket.onopen = function (evt) {
//websocket.readyState 属性:
/*
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.
*/
msg.innerHTML = websocket.readyState;
};
function song(){
var text = document.getElementById('text').value;
document.getElementById('text').value = '';
//向服务器发送数据
websocket.send(text);
}
//监听连接关闭
// websocket.onclose = function (evt) {
// console.log("Disconnected");
// };
//onmessage 监听服务器数据推送
websocket.onmessage = function (evt) {
msg.innerHTML += evt.data +'<br>';
// console.log('Retrieved data from server: ' + evt.data);
};
//监听连接错误信息
// websocket.onerror = function (evt, e) {
// console.log('Error occured: ' + evt.data);
// };
</script>
</html>