You can use socket.io and engine.io in WeChat mini programs
The websocket of the WeChat applet has been encapsulated once, resulting in the socket.io or engine.io client package being unable to be used directly. Based on the engine.io-client project, this project implements the transport layer of wxwebsocket so that it can be used in the applet. Use all the features of socket.io.
Note: The compiled package can only be used in WeChat mini programs
$ git clone https://github.com/wujjpp/socket.io.xcx.git
$ cd socket.io.xcx
$ npm install
$ npm run serve
Note: To run the test program, please turn on "The development environment does not verify the requested domain name and TLS version"
Copy dist/socket.io.xcx.min.js to your mini program source code and use it directly. For details, please refer to examples/app
This instance sends the hello
string to the server through emit message. After receiving it, the server emit message to the client.
client -> server: hello
server -> client: 'hello world '
~/examples/app/pages/index/index.js
// 导入socket.io小程序版包
import io from '../../socket.io.xcx.min'
// 使用IO创建socket实例,本实例使用本地socket.io服务器, 请根据根据实际情况修改IP
let socket = io ( 'ws://127.0.0.1:3000' )
function _setup ( ) {
var self = this ;
socket . on ( 'connect' , function ( ) {
console . log ( '连上了' ) ;
} ) ;
socket . on ( 'message' , function ( data ) {
self . data . messages . push ( data . message ) ;
self . setData ( {
messages : self . data . messages
} )
} ) ;
socket . on ( 'disconnect' , function ( ) {
console . log ( 'you have been disconnected' ) ;
} ) ;
}
Page ( {
data : {
messages : [ ]
} ,
onLoad : function ( ) {
_setup . apply ( this ) ;
} ,
send : function ( ) {
socket . emit ( 'message' , 'hello' ) ;
}
} )
~/examples/server/app.js
// Setup basic express server
var express = require ( 'express' ) ;
var app = express ( ) ;
var server = require ( 'http' ) . createServer ( app ) ;
var io = require ( 'socket.io' ) ( server ) ;
var port = process . env . PORT || 3000 ;
server . listen ( port , function ( ) {
console . log ( 'Server listening at port %d' , port ) ;
} ) ;
io . on ( 'connection' , function ( socket ) {
// when the client emits 'message', this listens and executes
socket . on ( 'message' , function ( data ) {
console . log ( 'message from client: ' , data ) ;
io . emit ( 'message' , {
message : data + ' world ' + new Date ( )
} ) ;
} ) ;
// when the user disconnects.. perform this
socket . on ( 'disconnect' , function ( ) {
// echo globally that this client has left
socket . broadcast . emit ( 'user left' , {
message : 'user left'
} ) ;
} ) ;
} ) ;
Made with ♥ by Wu Jian Ping