编写前端及服务器端代码
创立一个前端页面,连贯到本地的 WebSocket 服务器:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<input id="sendTxt" type="text">
<button id="sendBtn"> 发送 </button>
<div id="recv"></div>
</body>
<script type="text/javascript">
var wsServer = 'ws://127.0.0.1:8081';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {console.log("Connected to WebSocket server.");
document.getElementById("recv").innerHTML = "Connected to WebSocket server.";
};
websocket.onclose = function (evt) {console.log("Disconnected to WebSocket server.");
};
websocket.onmessage = function (evt) {console.log('Retrieved data from server:' + evt.data);
document.getElementById("recv").innerHTML = 'Retrieved data from server:' + evt.data;
};
websocket.onerror = function (evt, e) {console.log('Error occured:' + evt.data);
document.getElementById("recv").innerHTML = 'Error occured:' + evt.data;
};
document.getElementById("sendBtn").onclick = function() {var txt = document.getElementById("sendTxt").value;
websocket.send(txt);
}
</script>
</html>
创立一个 HTTP 服务器文件,用来接管前端的页面申请:
#!/usr/bin/env php
<?php
declare(strict_types=1);
$http = new Swoole\Http\Server("0.0.0.0", 80);
$http->on(
"request",
function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
$response->end(file_get_contents("./index.html")
);
}
);
$http->start();
创立一个 WebSocket 服务器文件,用来解决前端的 WebSocket 申请:
#!/usr/bin/env php
<?php
declare(strict_types=1);
echo "running...\n";
// 创立 WebSocket Server 对象,监听 0.0.0.0:8081 端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 8081);
$ws->on('open', function (Swoole\WebSocket\Server $ws, $request) {var_dump($request->fd, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
$ws->on('message', function (Swoole\WebSocket\Server $ws, $frame) {list($toFd, $message) = explode(" ", $frame->data);
echo "Message: {$frame->fd}:{$message}\n";
$ws->push($frame->fd, "{$message}");
global $ws;
// $ws->connections 遍历所有 websocket 连贯用户的 fd
foreach ($ws->connections as $fd) {
// 须要先判断是否是正确的 websocket 连贯,否则有可能会 push 失败
if ($ws->isEstablished($fd) && $fd == $toFd) {$ws->push($fd, "{$message}");
}
}
});
$ws->on('close', function (Swoole\WebSocket\Server $ws, $fd) {echo "client-{$fd} is closed\n";
});
$ws->start();
启动相干服务
启动容器及 HTTP 服务器:
docker run --rm -p 80:80 -p 8081:8081 --name swoole -v /d/swoole/www:/var/www phpswoole/swoole:4.5.9-php7.4
进入容器启动 WebSocket 服务器:
docker exec swoole bash
php ws.php
测试从前端页面收发音讯
关上一个标签页拜访:
另外关上一个标签页拜访:
在标签页 1 给标签页 2 发送音讯:
标签页 2 收到音讯:
标签页 2 给标签页 1 发送音讯:
标签页 1 收到音讯:
测试从后端程序收发音讯
编写一个客户端给标签页 1 和标签页 2 发送音讯:
<?php
Co\run(function () {$client = new Swoole\Coroutine\Http\Client("127.0.0.1", 8081);
$ret = $client->upgrade("/");
if ($ret) {$client->push("1 hello111");
$client->push("2 hello222");
var_dump($client->recv());
co::sleep(0.1);
}
});
执行客户端代码:
标签页 1 收到音讯:
标签页 2 收到音讯: