Using Socket.Io with Adonis3.0

Since inbuilt support for web sockets is missing in AdonisJs, using socket.io with AdonisJs is extremely simple.

Setting Up Socket.Io #

Using Existing Http connection is very common when starting a websocket server using socket.io. Let’s start by creating a socket.js file inside app/Http directory.

app/Http/socket.js #

'use strict'

module.exports = function (server) {

  const io = use('socket.io')(server)

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

}

This file exposes a function which accepts the HTTP server instance and using that instance you can create a web socket connection. Now you can approach socket.io the way you want.

Next you need to import this file inside bootstrap/http.js file. Just before the Server.listen import this file.

bootstrap/http.js #


use('App/Http/socket')(Server.getInstance())

Server.listen(Env.get('HOST'), Env.get('PORT'))
 
188
Kudos
 
188
Kudos

Now read this

# Petit mais grand (AdonisJs 3.2.1)

I am about to step the paddle for the major release of Adonisjs version 4.0 (called dawn). Dawn will be released with lots of exciting features including first class support for async/await, testing, tooling for deployment and bunch of ?... Continue →