node.js - 微信小程序 +nodejs+socket.io bug
問題描述
技術nodejs
socket.io
微信小程序
源碼server.js
const app = require(’express’)()const http = require(’http’).Server(app)const io = require(’socket.io’)(http)app.use(function(req, res, next) { res.setHeader(’Access-Control-Allow-Origin’, ’*’) res.setHeader(’Access-Control-Allow-Credentials’, true) res.setHeader(’Access-Control-Allow-Methods’, ’POST, GET, PUT, DELETE, OPTIONS’) next()})app.get(’/’, (req, res, next) => { res.send({ code: 200, message: ’Welcome to Chat’ })})io.on(’connection’, socket => { console.log(’a user connected’) socket .broadcast .emit(’connection’, ’恭喜您, 您已經連接上了我們的聊天室了, 現在您可以開始聊天了’) socket.on(’disconnect’, () => { console.log(’user disconnected’) }) socket.on(’chat message’, msg => { console.log(`message: ${msg}`) io.emit(’chat message’, msg) })})http.listen(3000, () => { console.log(’listening on *:3000’)})
client.js
onLoad(options) { // 頁面初始化 options為頁面跳轉所帶來的參數 // 創建一個 socket 連接 wx.connectSocket({ url: ’ws://localhost:3000’, data: {x: ’’,y: ’’ }, header: {’content-type’: ’application/json’ }, method: ’GET’, success: function (res) {console.log(’connect success: ’, res) }, fail: function (err) {console.log(’connect error: ’, err) } }) // 監聽websocket打開事件 wx.onSocketOpen(function (res) { console.log(’WebSocket連接已經打開!’) socketOpen = true for (var i = 0, len = socketMsgQueue.length; i < len; i++) {sendSocketMessage(socketMsgQueue[i]) } // 關閉socket wx.closeSocket() // socketMsgQueue = [] }) function sendSocketMessage(msg) { if (socketOpen) {wx.sendSocketMessage({data: msg}) } else {socketMsgQueue.push(msg) } } // 監聽WebSocket錯誤 wx .onSocketError(function (res) {console.log(’WebSocket連接打開失敗, 請檢查!’) }) // wx.sendSocketMessage 通過WebSocket連接發送數據, 需要先先 wx.connectSocket, 并在 // wx.onSocketOpen 回調之后才能發送 監聽WebSocket 接收到拂去其的消息事件 wx.onSocketMessage(function (res) { console.log(’收到服務器內容: ’ + res.data) }) // 關閉WebSocket連接 監聽websocket連接 wx.onSocketClose(function (res) { console.log(’WebSocket 已關閉!’) })BUG
WebSocket connection to ’ws://localhost:3000/’ failed: Connection closed before receiving a handshake response
為什么在握手前就斷開連接了?
已知的問題是:
微信小程序必須要 wss協議
在客戶端如果用 socket.io方式就可以,換成 html5的websocket 或 微信小程序內置的socket方式 都不行(socket.io使用的是http協議)。
想知道的是:
微信小程序可以設置 socket以 http 協議請求嗎?或者有什么有得解決方法?
問題解答
回答1:微信小程序 websocket 協議版本為13 你可以抓包看下而 socket.io 支持的協議版本為4 socket.io-protocol
ws支持協議版本13 可以用ws包或者以他為依賴的中間件ws
相關文章:
1. python - linux怎么在每天的凌晨2點執行一次這個log.py文件2. 關于mysql聯合查詢一對多的顯示結果問題3. 實現bing搜索工具urlAPI提交4. MySQL主鍵沖突時的更新操作和替換操作在功能上有什么差別(如圖)5. 數據庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。6. windows誤人子弟啊7. mysql優化 - MySQL如何為配置表建立索引?8. 如何用筆記本上的apache做微信開發的服務器9. 我在網址中輸入localhost/abc.php顯示的是not found是為什么呢?10. 冒昧問一下,我這php代碼哪里出錯了???
