第一步。下載swoole
-
wget https:
-
tar zxvf swoole-1.8.11.tgz
-
cd swoole-1.8.11
-
phpize
-
./configure
-
make && make install
第二步,配置PHP.ini
-
vi /etc/php.ini
-
新增以下內容
-
extension=swoole.so
重啟nginx/apache
在web根目錄
-
vi server.php
-
-
-
<?php
-
-
-
$ws = new swoole_websocket_server("0.0.0.0", 9502);
-
-
-
$ws->on('open', function ($ws, $request) {
-
var_dump($request->fd, $request->get, $request->server);
-
$GLOBALS['fd'][] = $request->fd;
-
-
});
-
-
-
$ws->on('message', function ($ws, $frame) {
-
echo "Message: {$frame->data}\n";
-
foreach($GLOBALS['fd'] as $key => $val){
-
$ws->push($val,$frame->data);
-
}
-
-
});
-
-
-
$ws->on('close', function ($ws, $fd) {
-
echo "client-{$fd} is closed\n";
-
});
-
-
$ws->start();
啟動服務
本地新建檔案
-
<!DOCTYPE html>
-
<html lang="en">
-
<head>
-
<meta charset="UTF-8">
-
<title></title>
-
</head>
-
<body>
-
<input type="text" id="color">
-
<button onclick="doSend()">變色</button>
-
</body>
-
</html>
-
<script>
-
var wsServer = 'ws://192.168.1.212:9502'; //ip地址為伺服器IP地址
-
var websocket = new WebSocket(wsServer);
-
websocket.onopen = function (evt) {
-
console.log("Connected to WebSocket server.");
-
};
-
-
websocket.onclose = function (evt) {
-
console.log("Disconnected");
-
};
-
-
websocket.onmessage = function (evt) {
-
-
document.body.style.backgroundColor="#"+evt.data;
-
console.log('Retrieved data from server: ' + evt.data);
-
};
-
-
websocket.onerror = function (evt, e) {
-
console.log('Error occured: ' + evt.data);
-
};
-
function doSend() {
-
var color = document.getElementById("color").value;
-
websocket.send(color);
-
}
-
</script>
測試:
可以多開幾個頁面,在任意一個頁面輸入6位顏色編碼後,所有頁面背景顏色均會改變。