search
HomeWeChat AppletMini Program DevelopmentDetailed example of how to use Socket in WeChat applet

This article mainly introduces relevant information to you about the examples of using Socket in WeChat applet. I hope this article can help you. Friends in need can refer to it. I hope it can help everyone.

Example of WeChat applet using Socket

First of all, a small program can only have one WebSocket connection at the same time. If there is already a WebSocket connection, it will Close the current connection and re-establish a connection.

Secondly, if appID is used, the protocol must be wss://...

Recently, the team used a small program to make market quotations. When connecting to the socket, it was found that the subscriber had not yet subscribed. Under the circumstances, the broadcast was carried out directly and the socket connection was automatically closed.

Time was tight and I was scratching my head, so I quoted socket-io (a websocket imitation based on a small program, socket-io, which is not an official socket) -io, portal), usage method:

1. First paste an io js

2 in the utils folder, then npm install wxapp-socket-io

3. Create a new socket.js under the config folder to encapsulate the socket connection, as follows:

const io = require('../utils/io.js')
let url = 'wss://......'
let wsStatus = false
let onSocket = null
export const connect = function(cb){
  if(!onSocket){
    onSocket = io(url)
    onSocket.on('connect', function (res) {
      cb(true,onSocket)
      wsStatus = true
    })
    setTimeout(function(){
      if(!wsStatus){
        cb(false,onSocket)
      }
    },10000)
  }else{
    cb(true,onSocket)
  }
}

4. Call the global encapsulation subscription method on the page to be referenced

let openSocket = require('../../config/socket')
let app = getApp()
let socket = null
Page({
data: {
  zl: [[422, 400, 468, 834, 785, 446, 845, 517, 630, 797, 890, 529, 553, 425, 469, 470, 837, 841, 521, 525], [422, 400, 468, 834, 785, 446, 845, 517, 630, 797, 890, 529, 553, 425, 469, 470, 837, 841, 521, 525]]
},
onLoad: function () {
  let that = this;
  //socket调用
  openSocket.connect(function (status, ws) {
    if (status) {
      socket = ws
      this.subscribe('zl')//对封装好对订阅方法进行调用
      socket.on('broadcast', function (msg) {//广播
        console.log("broadcast");
        console.log(msg);
      })
    } else {
      alert("socket 连接失败")
    }
  });
},
subscribe: function (type) {
  if (socket) {
    let eis = this.data[type]
    if (eis && eis.length > 0) {
      let param = {//仅供参考,根据接口自行更改
        eis: eis.join(',')
      }
      socket.emit('subscribe', JSON.stringify(param));
    }
  }
}
});

Related recommendations:

HTML5 WebSocket peer-to-peer chat implementation method

node.js Use socket to implement chat instance sharing

Detailed explanation of php Implement socket push technology

The above is the detailed content of Detailed example of how to use Socket in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor