第一步。下载swoole
wget https://pecl.php.net/get/swoole-1.8.11.tgz
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
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$GLOBALS['fd'][] = $request->fd;
//$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
foreach($GLOBALS['fd'] as $key => $val){
$ws->push($val,$frame->data);
}
//$ws->push($frame->fd, "{$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
启动服务
php server.php
本地新建文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="color">
<button οnclick="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) {
//alert(evt.data)
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位颜色编码后,所有页面背景颜色均会改变。