TypechoJoeTheme

404

swoole消息推送

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

赞 · 0
评论 (0)

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

标签云

暂无标签