Using Socket.io with Adonis

Adonis has gained traction since its launch, and I have received a couple of requests on how to integrate socket.io with Adonis.

Check out adonis official docs

I am working v2 that will have 1st class support for socket.io.

Here I will explain the simplest way to use socket.io with Adonis.

Install socket.io

npm install socket.io --save  

 

Setting up

With socket.io installed, you have to create a file inside app/Http/ folder called socket.js and put following into it.

app/Http/socket.js

const server = use('http').createServer()  
const io = use('socket.io')(server)  
io.on('connection', function (socket) {  
    console.log('connection created >>>')
})
io.listen(3000)  

Now we have created the socket.js file but we need to load it while booting our server.

boostrap/http.js

After use('App/Http/routes') include our newly created socket.js file.

/*
|-----------------------------------------------------------
|   Loading Socket.io File
|----------------------------------------------------------
|
|   Here we register socket.js file to work with socket.io
|
*/
use("App/Http/socket")  

 

Client

From here you can follow the normal process to setup socket.io on the client end.

Go to https://cdnjs.com/ and search for socket.io

Place following inside your resources/views/partials/master.html file.

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script>
  <script>
  var socket = io('http://localhost:3000');
  </script>

 

Start Server

npm start  

Bingo! , that's all you need to setup socket.io in your Adonis app.

I agree this is not the best way to do it, but until v2.0 this may be the simplest way to do it.