Skip to content

Instantly share code, notes, and snippets.

@reg2005
Last active Jun 7, 2020
Embed
What would you like to do?
How setup socket.io to adonisJS 5 (preview version)
  1. Add all *.ts files from this gist to your project
  2. Add "./providers/SocketIOProvider" in .adonisrc.json section "providers"
  3. Add "./start/socket" in .adonisrc.json section "preloads"
  4. npm i --save socket.io socket.io-redis @types/socket.io
  5. Add "@types/socket.io" in "types" array tsconfig.json
  6. Connect to your WS ws://localhost:3333/socket.io
  7. See your adonis logs when client connect
// start/socket.ts
import SocketIO from '@ioc:Socket.IO'
SocketIO.afterStart(() => {
const io = SocketIO.io()
io.on('connection', function (socket) {
io.emit('sdfsdf', 'sdfsdf')
console.log(socket.id)
})
io.of('/rouletteGame')
.on('connection', function (socket) {
console.log(socket.id)
socket.emit('sdsdfsdf')
})
})
// contracts/socketIO.ts
declare module '@ioc:Socket.IO' {
import SocketIO from 'socket.io'
import { Server } from 'socket.io'
export function io(): Server
export function afterStart(cb: () => void): void
}
// providers/SocketIOProvider.ts
import { IocContract } from '@adonisjs/fold'
import SocketIO from 'socket.io'
import { ServerContract } from '@ioc:Adonis/Core/Server'
import { ConfigContract } from '@ioc:Adonis/Core/Config'
//import redisAdapter from 'socket.io-redis'
class SocketIOInstance{
private server: ServerContract
private config: ConfigContract
private afterStartCB: () => void
private ioInstance = SocketIO()
constructor (Server: ServerContract, Config: ConfigContract){
this.server = Server
this.config = Config
}
public afterStart (cb: () => void){
this.afterStartCB = cb
}
public start (){
const { host, port } = this.config.get('redis.connections.local')
this.ioInstance = SocketIO(this.server.instance)
//this.ioInstance.adapter(redisAdapter({ host, port }))
if (typeof this.afterStartCB === 'function'){
this.afterStartCB()
}
console.log('SocketIO started')
}
public io (){
return this.ioInstance
}
}
export default class SocketIOProvider {
constructor (protected $container: IocContract) {
}
public register () {
// Register your own bindings
this.$container.singleton('Socket.IO', () => {
const Server: ServerContract = this.$container.use('Adonis/Core/Server')
const Config: ConfigContract = this.$container.use('Adonis/Core/Config')
return new SocketIOInstance(Server, Config)
})
}
public boot () {
}
public shutdown () {
// Cleanup, since app is going down
}
public ready () {
// When app and http server are ready
const SocketIO = this.$container.use('Socket.IO')
SocketIO.start()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment