WeChat applet real-time communication (websocket) problem

Don't be busy on duty these days. Artificial intelligence is all scattered. Let's write real-time communication of writing small programs today.
Applet:
// This is the connection

lianjie:function(){
 var socketOpen = false
//注册信息
var data = { appid: "77494ad321405fb340e2d1a664850954", sid: "123" }
var socketMsgQueue = JSON.stringify(data)
console.log(socketMsgQueue)
//建立连接
wx.connectSocket({
  url: "wss://websck.eloeg.wang:20001",
})
//
wx.onSocketOpen(function (res) {
  console.log('WebSocket连接已打开!')
  socketOpen = true
  console.log('数据发送中' + socketMsgQueue)
  sendSocketMessage(socketMsgQueue)
})
function sendSocketMessage(msg) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data: msg
    })
  } else {
    socketMsgQueue.push(msg)
  }
}
wx.onSocketError(function (res) {
  console.log('WebSocket连接打开失败,请检查!')
})
wx.onSocketMessage(function (res) {
  console.log('收到服务器内容:' + JSON.stringify(res))
})

},
// Simulation of sending data, because the user sid registered to himself when establishing a connection is: 123, the data sent is also sent to the user with sid 123, that is, the data is ok12

fasong:function(){
wx.request({
  url: 'https://wss.md.eloeg.wang/erweima/fasong.php',
  method: 'GET',
  header: { 'content-type': 'application/json' },
  data: {
    sid:'123',
    data:"ok12"
  },
  success: function (res) {
    console.log(res)
  }
})

} The
effect is shown in the figure: the php code of the back end:
image description

<?php 
 $appid = '77494ad321405fb340e2d1a664850954'; //填写socket端的appid  
 $appkey = '****************************'; //填写socket端的sercret 
 $apiUrl = '*******************';//发送接口
 $sid=$_GET["sid"];
 $data = $_GET["data"]; //要发送的消息
 $signature = md5($appid.$sid.$data.$appkey);
 $url = $apiUrl.'?appid='.$appid.'&sid='.$sid.'&data='.$data.'&signature='.$signature;
 $html=file_get_contents($url);
 echo $html;
?>
朋友帮助弄了个workerman的接口,直接进行调用了。所以看起来很简单,这个sid是要给用户进行标记用,要给哪个用户发消息,就在发送时将其sid传送至后台。

Guess you like

Origin www.cnblogs.com/10manongit/p/12726777.html