我正在使用 Adonis 4.1.0 并且 Adonis-websocket 仅可用于 v3 。谁能告诉我在 Adonis 4.1.0 中使用 socket.io 的解决方法?

最佳答案

显然他们不久前一直在研究这个,它是基于 socket.io 但由于内存泄漏等一些问题,他们决定直接使用 websockets 代替,检查这些讨论:
https://github.com/adonisjs/discussion/issues/51
https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519

您是否尝试过使用 socket.io 而不依赖 Adonis ? ,
就像是 :

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

但是你现在应该可以用 Adonis 做到这一点,根据:https://github.com/adonisjs/adonis-websocket-protocol

例子 :
const filereader = require('simple-filereader')
const msgpack = require('msgpack-lite')
const packets = require('@adonisjs/websocket-packets')

const client = new WebSocket('ws://localhost:3000/adonis-ws')

client.onopen = function () {
  // TCP connection created
}

client.onerror = function () {
  // TCP connection error
}

client.onmessage = function (message) {
  filereader(message, function (error, payload) {
    const packet = msgpack.decode(payload)
    handlePacket(packet)
  })
}

function handlePacket (packet) {
  if (packets.isOpenPacket(packet)) {
    console.log('Server ack connection. Make channel subscriptions now')
  }

  if (packets.isJoinAck(packet)) {
    console.log('subscription created for %s', packet.d.topic)
  }
}

使用 WS 检查广播示例:https://github.com/websockets/ws#broadcast-example

关于node.js - Socket.io 与 Adonis.js,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49356813/

10-16 11:17