參考:node
由於項目需求,後端要使用nodejs簡單搭建一個服務器,通信用json格式。github
使用Egret提供的socket.io庫express
https://github.com/egret-labs/egret-game-libraryjson
若是直接使用這個socket.io庫,在微信小遊戲中會報錯。後端
例如io is not defined , socket.io.js中有用到document等等。因而網上找了找別人的解決方法。服務器
1. 下載weapp.socket.io微信
https://github.com/weapp-socketio/weapp.socket.io微信開發
2. 配置weapp.socket.ioapp
2.1 下載解壓後放在微信項目library下
2.2 在game.js中引入weapp.socket.io.js
在微信小遊戲項目在找到game.js,並添加以下代碼
window.io = require("./library/weapp.socket.io.js");
2.3 在Egret項目任一.ts文件下定義一個全局io (我是定義在本身的Socket工具類ClientSocket.ts中)
declare let io: any; declare interface Window { io: any }
3.1 本地搭建一個服務器 (具體nodejs如何搭建服務器這裏就不寫了)
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.send('<h1>Welcome Realtime Server</h1>'); }); http.listen(3004, function(){ console.log('listening on *:3004'); }); io.on('connection', function(socket){ console.log('a user connected'); });
3.2 客戶端代碼
客戶端鏈接本地服務器127.0.0.1:3004,鏈接成功後輸出connect success。
let socket; socket = io.connect("http://127.0.0.1:3004",{ reconnection: false,'force new connection': true}); socket.on('connect',function() { egret.log("connect success"); });
微信開發者工具輸出success,表示鏈接成功