-
nodejs
-
socket.io
-
微信小程序
server.js
- 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)
- }
- // 关闭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 已关闭!')
- })
- 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 协议请求吗?或者有什么有得解决方法?
参考解答:解答者:alicorn
微信小程序 websocket 协议版本为13 你可以抓包看下
而 socket.io 支持的协议版本为4 socket.io-protocolws支持协议版本13 可以用ws包或者以他为依赖的中间件ws