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', '恭喜您, 您已經(jīng)連接上了我們的聊天室了, 現(xiàn)在您可以開始聊天了')
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為頁面跳轉(zhuǎn)所帶來的參數(shù)
// 創(chuàng)建一個 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)
}
})
// 監(jiān)聽websocket打開事件
wx.onSocketOpen(function (res) {
console.log('WebSocket連接已經(jīng)打開!')
socketOpen = true
for (var i = 0, len = socketMsgQueue.length; i < len; i++) {
sendSocketMessage(socketMsgQueue[i])
}
// 關(guān)閉socket
wx.closeSocket()
// socketMsgQueue = []
})
function sendSocketMessage(msg) {
if (socketOpen) {
wx.sendSocketMessage({data: msg})
} else {
socketMsgQueue.push(msg)
}
}
// 監(jiān)聽WebSocket錯誤
wx
.onSocketError(function (res) {
console.log('WebSocket連接打開失敗, 請檢查!')
})
// wx.sendSocketMessage 通過WebSocket連接發(fā)送數(shù)據(jù), 需要先先 wx.connectSocket, 并在
// wx.onSocketOpen 回調(diào)之后才能發(fā)送 監(jiān)聽WebSocket 接收到拂去其的消息事件
wx.onSocketMessage(function (res) {
console.log('收到服務(wù)器內(nèi)容: ' + res.data)
})
// 關(guān)閉WebSocket連接 監(jiān)聽websocket連接
wx.onSocketClose(function (res) {
console.log('WebSocket 已關(guān)閉!')
})
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
為什么在握手前就斷開連接了?
已知的問題是:
微信小程序必須要 wss協(xié)議
在客戶端如果用 socket.io
方式就可以,換成 html5的websocket
或 微信小程序內(nèi)置的socket方式
都不行(socket.io使用的是http協(xié)議
)。
想知道的是:
微信小程序可以設(shè)置 socket以 http 協(xié)議請求嗎?或者有什么有得解決方法?
走同樣的路,發(fā)現(xiàn)不同的人生
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