本文主要和大家介绍微信小程序使用Socket的实例的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下,希望能帮助到大家。
微信小程序使用Socket的实例
首先,一个小程序同时只能有一个WebSocket连接,如果当前已经存在一个WebSocket连接,会关闭当前连接,并重新建立一个连接。
其次,如果使用了appID,协议必须是 wss://...
最近团队用小程序做行情,在连接socket的时候,发现在还没有进行subscribe的情况下,就直接进行了广播,并且自动关闭了socket连接,
时间紧迫,抓耳挠腮,遂引用了socket-io(基于小程序的websocket仿写的socket-io,并非官方的socket-io,传送门),使用方法:
1、先在utils文件夹粘贴一个io的js
2、然后 npm install wxapp-socket-io
3、config文件夹下新建一个socket.js,对socket连接进行封装,如下:
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、在要引用的页面调用,全局封装订阅方法
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)); } } } });
相关推荐:
Atas ialah kandungan terperinci 实例详解微信小程序如何使用Socket. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

PhpStorm versi Mac
Alat pembangunan bersepadu PHP profesional terkini (2018.2.1).

Versi Mac WebStorm
Alat pembangunan JavaScript yang berguna

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

SublimeText3 Linux versi baharu
SublimeText3 Linux versi terkini

Penyesuai Pelayan SAP NetWeaver untuk Eclipse
Integrasikan Eclipse dengan pelayan aplikasi SAP NetWeaver.