Tijan Manandhar
Tijan Manandhar

Reputation: 332

Socket.io with Adonis.js

I am using Adonis 4.1.0 and Adonis-websocket is only been available for v3. Can anyone tell me workaround for using socket.io with Adonis 4.1.0?

Upvotes: 4

Views: 6712

Answers (3)

Vishnu Bhadoriya
Vishnu Bhadoriya

Reputation: 1676

create a standalone socket io configuration file in start/socket.js

const io = require('socket.io')();
io.listen(3000);
io.on('connection', function (socket) {
  console.log(socket.id)
})

to start your socket io server you can configure your server.js as below

new Ignitor(require('@adonisjs/fold'))
  .appRoot(__dirname)
  .preLoad('start/socket') //path of socket.js
  .fireHttpServer()
  .catch(console.error)

now when you start your server then it will start along with socket io

Upvotes: 0

Tiago Mendes
Tiago Mendes

Reputation: 11

Create start/socket.js file and paste following code inside it.

const Server = use('Server')
const io = use('socket.io')(Server.getInstance())

io.on('connection', function (socket) {
console.log(socket.id)
})

From Virk Himself in this forum:https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519

Upvotes: 1

Taki
Taki

Reputation: 17654

apparently they have been working on this not long ago, it was based on socket.io but because of some issues like memory leaks and others, they decided to use websockets directly instead, check these discussions :
https://github.com/adonisjs/discussion/issues/51
https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519

have you tried using socket.io without relying on Adonis ? , something like :

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');
});

But you should be able to do this with Adonis by now according to : https://github.com/adonisjs/adonis-websocket-protocol

Example :

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)
  }
}

check this for broadcast examples using WS : https://github.com/websockets/ws#broadcast-example

Upvotes: 2

Related Questions