server.php
$ws = new swoole_websocket_server("0.0.0.0", 9501);
//监听WebSocket连接打开事件
$ws->on('open', function ($server, $request) {
echo "用户连接上来了".PHP_EOL;
});
//监听WebSocket消息事件
$ws->on('message', function ($server, $frame) {
$data = $frame->data;
foreach($server->connection_list() as $v){
$server->push($v,$data);
}
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($server, $fd) {
echo "用户连接关闭".PHP_EOL;
});
$ws->start();
push.html
<script>
ws = new WebSocket('ws://127.0.0.1:9501');
ws.onopen = function(event)
{
ws.send("hello");
console.log("发送成功");
}
ws.onmessage = function (evt)
{
var msg = evt.data;
alert("数据已接收..."+msg);
};
ws.onclose = function (e)
{
alert("连接失败");
}
</script>
小程序
onLoad: function () {
console.log('开始');
var that = this
var url = 'ws://127.0.0.1:9501';
wx.connectSocket({
url: url,
});
wx.onSocketMessage((res) => {
console.log(res)
var text = res.data + "\n"; //通过\n实现换行再重新赋值
wx.showModal({
title:'消息提示',
content:text,
success:function(res){
}
})
})
}
php server.php 启动服务
进入push.html页面 会推送一条hello 小程序会弹出hello
点击链接加入群聊:企鹅群:827944755