测试版本
虚拟机案例地址 http://192.168.13.121/swoole_file_frontend/demo/index.html
服务器要求
1.安装并启用swoole组件 https://segmentfault.com/a/1190000008285814 安装方式大同小异
2.编辑一个启动webSocket的server.php文件
~~~
<?php
//连接本地的 Redis 服务
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set("fd", "[]"); //每次第一次执行都需要先清空reids里面的标识
$server = new swoole_websocket_server("0.0.0.0", 9502);
$server->on('open', function (swoole_websocket_server $server, $request) use($redis) {
echo "访客{$request->fd}进来了\n";
$server->push($request->fd, "{$request->fd}客户进来了");
$str = json_decode($redis->get("fd"), true);
if($str == "") $str = [];
if(!in_array($request->fd, $str)){
array_push($str, $request->fd);
$str = json_encode($str);
$redis->set("fd", $str);
echo "目前在线访客:";
print_r($redis->get("fd"));
}
});
$server->on('message', function (swoole_websocket_server $server, $frame) use($redis) {
echo "系统消息说:{$frame->data}\n";
$str = json_decode($redis->get("fd"), true);
foreach ($str as $key => $value) {
if($frame->fd != $value){
$server->push($value, "系统消息说:".$frame->data);
}
}
});
$server->on('close', function ($ser, $fd) use($redis) {
echo "client {$fd} closed\n";
$str = json_decode($redis->get("fd"), true);
$point = array_keys($str, $fd, true); //search key
array_splice($str, $point['0'],1); //delete array
$str = json_encode($str);
$redis->set("fd", $str);
echo "删除后在线访客:";
print_r($redis->get("fd"));
});
$server->start();
~~~
3.服务器安全测试开放9502端口,服务器内部开发端口或者直接关闭防火墙
4.启动server.php
~~~
php /data/wwwroot/default/swoole_file_frontend/demo/server.php
~~~
5.前端文件准备,因为是消息推送模拟,需要一个页面admin.html做后端消息推送页面,另外一个页面client.html做用户客户端消息接收页面,核心内容差不多,样式可以替换
admin.html
~~~
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
<title>AUI</title>
<link rel="stylesheet" type="text/css" href="../css/aui.css"/>
</head>
<body>
<header class="aui-bar aui-bar-nav aui-title-fixed" id="aui-header">
<a class="aui-btn aui-pull-left" href="index.html" tapmode >
<span class="aui-iconfont aui-icon-left"></span>
</a>
<div class="aui-title" id="aui-title">swoole websocket</div>
</header>
<section class="aui-chat main-margin-top">
<div class="aui-content aui-margin-b-15">
<ul class="aui-list aui-form-list">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label">
消息
</div>
<div class="aui-list-item-input">
<input type="text" name="content" placeholder="请输入需要推送的信息">
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner aui-list-item-center aui-list-item-btn">
<div class="aui-btn aui-btn-info aui-margin-r-5" id="fun_initWebSocket">连接</div>
<div class="aui-btn aui-btn-info aui-margin-r-5" id="push_button">推送</div>
<div class="aui-btn aui-btn-danger aui-margin-l-5" id="fun_close">断开</div>
</div>
</li>
</ul>
</div>
</section>
<section class="aui-chat main-margin-top">
<div class="aui-content aui-margin-b-15">
<ul class="aui-list aui-form-list">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label">
打印
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner aui-list-item-center aui-list-item-btn" >
<p id="prints"></p>
</div>
</li>
</ul>
</div>
</section>
</body>
<script>
var socket = null;
var prints = null;
var push_content = null;
window.onload = function () {
//验证浏览器是否支持WebSocket协议
if (!window.WebSocket) {
alert("WebSocket not supported by this browser!");
}
var push_button = document.getElementById("push_button");
var fun_close = document.getElementById("fun_close");
var fun_initWebSocket = document.getElementById("fun_initWebSocket");
var push_content = document.getElementsByName("content");
prints = document.getElementById("prints");
push_button.onclick = function () {
if(socket != null && socket.readyState==1){
prints.innerHTML = '发送信息:'+push_content['0'].value;
socket.send(push_content['0'].value);
}else{
prints.innerHTML ='握手失败,无法推送信息 ';
// console.log("");
}
}
fun_close.onclick = function () {
if(socket != null && socket.readyState==1){
prints.innerHTML = '关闭当前连接';
//console.log("关闭当前连接");
socket.close();
}
}
fun_initWebSocket.onclick = function () {
if(socket == null || socket.readyState!=1){
socket = new WebSocket('ws://47.93.190.214:9502'); //监听端口
prints.innerHTML = '握手成功';
reconnect ();
}
}
};
function reconnect (){
socket.onmessage = function (event) { // **接收到服务器数据**触发
// alert('Received data: ' + event.data); //这里应该返回发送成功的额标识
//console.log('Received data: ' + event.data);
prints.innerHTML = event.data;
};
socket.onopen = function () { //监听是否连接服务器成功触发
// socket.send(push_content['0'].value); //重要!!客户端返回服务器
// console.log("握手成功");
//prints.append('握手成功 \n ');
socket.send('hello world!!!');//向php服务器发送数据
};
socket.onclose = function () { //与服务器连接断开触发
//console.log('Lost connection!');
prints.innerHTML = '当前连接已关闭!';
};
socket.onerror = function () { //与服务器连接出现错误触发
prints.innerHTML = 'Error';
// console.log('Error!');
};
}
</script>
</html>
~~~
client.html
~~~
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
<title>AUI</title>
<link rel="stylesheet" type="text/css" href="../css/aui.css"/>
</head>
<body>
<header class="aui-bar aui-bar-nav aui-title-fixed" id="aui-header">
<a class="aui-btn aui-pull-left" href="index.html" tapmode >
<span class="aui-iconfont aui-icon-left"></span>
</a>
<div class="aui-title" id="aui-title">swoole websocket</div>
</header>
<section class="aui-content">
<ul class="aui-list">
<li class="aui-list-header">
消息通知:
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<p id="push_content"></p>
</div>
</li>
</ul>
</section>
</body>
<script>
var socket = new WebSocket('ws://47.93.190.214:9502'); //监听端口
socket.onopen = function () { //监听是否连接服务器成功触发
console.log('Connected!');
//socket.send("这条信息会返回给服务器看"); //重要!!客户端返回服务器
};
socket.onmessage = function (event) { // **接收到服务器数据**触发
console.log(event.data);
// alert('Received data: ' + event.data);
document.getElementById("push_content").innerHTML = event.data;
// socket.close();
};
socket.onclose = function () { //与服务器连接断开触发
console.log('Lost connection!');
};
socket.onerror = function () { //与服务器连接出现错误触发
console.log('Error!');
};
// socket.send('hello, world!');
</script>
</html>
~~~
运行效果图1.服务器控制台
![](https://box.kancloud.cn/e219ed4ca147bdc27e5982d0737ee2a1_753x548.png)
运行效果图2.360急速浏览器+火狐浏览器
![](https://box.kancloud.cn/7a9f804f35d3615efb7b0fa3c0a0c902_1532x1048.png)