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. angular.js - 不适用其他构建工具,怎么搭建angular1项目2. python如何不改动文件的情况下修改文件的 修改日期3. mysql - 一个表和多个表是多对多的关系,该怎么设计4. javascript - git clone 下来的项目 想在本地运行 npm run install 报错5. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?6. android-studio - Android 动态壁纸LayoutParams问题7. 主从备份 - 跪求mysql 高可用主从方案8. angular.js - 三大框架react、vue、angular的分析9. python 如何实现PHP替换图片 链接10. python - django 里自定义的 login 方法,如何使用 login_required()
