sudo apt-get install curl
2.安裝 composer
$curl -sS https://getcomposer.org/installer | php
$sudo mv composer.phar /usr/local/bin/composer
$sudo chmod +x /usr/local/bin/composer
$composer
3.建立 composer.json
$sudo touch composer.json
$sudo pico composer.json
其內容為
{
"require": {
"jsnlib/swoole": "^1.0"
}
}
4.安裝套件
$composer update
5.建立與編輯 swoole_advanced.php
$sudo touch swoole_advanced.php
$sudo pico swoole_advanced.php
swoole_advanced.php 所在的IP: 192.168.32.106
其內容為
<?php
require_once 'vendor/autoload.php';
// 建立 websocket 物件,監聽 192.168.32.106:8080 連接埠
$ws = new swoole_websocket_server("192.168.32.106", 8080);
// 監聽 WebSocket 連接打開事件
$ws->on('open', function ($ws, $request) {
echo "進入者編號:{$request->fd}\n";
});
// 監聽 WebSocket 訊息事件
$ws->on('message', function ($ws, $frame) {
echo "收到進入者 {$frame->fd} 訊息: {$frame->data} \n";
\Jsnlib\Swoole::push_all([
'ws' => $ws,
'self' => $frame->fd,
'is_send_self' => false,
'data' => $frame->data
]);
});
// 今天 WebSocket 連接關閉事件
$ws->on('close', function ($ws, $fd) {
echo "離開者編號:{$fd}\n";
});
$ws->start();
?>
6.建立 client_swoole_advance.html
$sudo touch client_swoole_advance.html
$sudo pico client_swoole_advance.html
client_swoole_advance.html 所在位置IP:192.168.32.182,/home/webadmin/html/
其內容為
<!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>Document</title>
<script>
var wsServer = 'ws://192.168.32.106:8080';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("成功連接到 WebSocket 服務");
};
websocket.onclose = function (evt) {
console.log("關閉連接 WebSocket 服務");
};
websocket.onmessage = function (evt) {
console.log('伺服器顯示:' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('發生錯誤: ' + evt.data);
};
// 發送訊息給所有人
const send_msg = function (){
var name = document.getElementsByClassName('name')[0].value;
var msg = JSON.stringify({
message: '你好,我是' + name,
})
websocket.send(msg)
}
</script>
</head>
<body>
<input type="text" class="name" placeholder="請輸入姓名" autofocus>
<input type="submit" value="發送" onclick="send_msg(); ">
</body>
</html>
7.server端 在終端機啟動 swoole_advance.php
$php swoole_advance.php
8.client端 用瀏覽器 chrome 打開 或是 指令開啟
$cd /home/webadmin/html
$google-chrome client_swoole_advance.html
此時,server端會出現進入者編號:1
client端 開啟[開發人員工具]
可以看到
此時,若在[請輸入姓名],輸入Jack後,按下[發送]
server端會出現 收到進入者 1 訊息: {"message":"你好,我是Jack"}
開啟第二個分頁,並將第一分頁的網址貼上,然後打上[ Wood ],按下送出。如下圖:
server端會出現此時,第一分頁則會出現
資料來源:
1.php – swoole – 架設 websocket 進階範例
沒有留言:
張貼留言