search

Home  >  Q&A  >  body text

node.js - 微信小程序 +nodejs+socket.io bug

技术

源码

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

为什么在握手前就断开连接了?

已知的问题是:

  1. 微信小程序必须要 wss协议

  2. 在客户端如果用 socket.io方式就可以,换成 html5的websocket微信小程序内置的socket方式 都不行(socket.io使用的是http协议)。

想知道的是:

  1. 微信小程序可以设置 socket以 http 协议请求吗?或者有什么有得解决方法?

怪我咯怪我咯2781 days ago948

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 15:33:50

    The websocket protocol version of the WeChat applet is 13. You can capture the packet and check it out
    The protocol version supported by socket.io is 4 socket.io-protocol

    ws supports protocol version 13. You can use the ws package or the middleware ws that relies on it

    reply
    0
  • Cancelreply