Ad

Socket.io Extend Socket Class

- 1 answer

I want to create a new function for the Socket class in socket.io but i have no idea how to accomplish this.

I would like to call the function like this socket.nearby().emit().

My code below:

const server = require('http').createServer()
const socketio = require('socket.io')
const io = socketio(server)

io.on('connection', (socket) => {
    socket.on('join', (data, callback) => {
        // process data

        socket.nearby().emit('join', data)

        callback(data)
    })
})

io.prototype.nearby = function() {
    // do function
}
Ad

Answer

io is not the constructor for the socket.io Socket class so that's why what you showed wouldn't work as you don't have the correct prototype.

The simplest way, without delving into the socket.io source code to try to find how you can access the socket prototype, would be to just do this:

const server = require('http').createServer()
const socketio = require('socket.io')
const io = socketio(server)

io.on('connection', (socket) => {

    // add our custom method to each newly created socket object
    socket.nearby = function() {
        // add implementation code here
    }

    socket.on('join', (data, callback) => {
        // process data

        socket.nearby().emit('join', data)

        callback(data)
    })
})
Ad
source: stackoverflow.com
Ad