Boris K
Boris K

Reputation: 3580

Dynamically joining rooms in Vue SocketIO

I am using Vue SocketIO on the front end, and would like my application to join rooms dynamically, based on user input.

This feature is not yet available in the package (the author has been working on it,) and I was wondering about ways to hack it together.

I am setting up SocketIO in my main application file like this:

import VueSocketIO from 'vue-socket.io'
import io from 'socket.io-client';

const token = window.localStorage.getItem('token');
const socketInstance = io(require('../config/web').socket_url, {
    transports: ['websocket', 'polling'],
    transportOptions: {
        polling: {
            extraHeaders: {
                Authorization: token
            }
        }
    }
});
Vue.use(new VueSocketIO({
    debug: true,
    connection: socketInstance,
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    }
}));

In my component, I am attempting to join like this,

selectSession () {
                console.log(this.$socket)
                // this.$socket.join(this.subscribedSession)
            }

which fails since this.$socket has no join method.

Anyone have an idea of how to hack this?

Upvotes: 0

Views: 3052

Answers (1)

Patrick Hollweck
Patrick Hollweck

Reputation: 6665

This is not a problem with the VueSocketIO package or even the socket.io-client

The vue.$socket is a socket.io-client instance and therefore has all features the native client provides.

The problem is that you cannot join rooms from the client-side, this is a server-side only feature.

If you look at the native socket.io client API docs you will find that there is no join method on the client object, not because they have not implemented it but because it can by design not exist

So how can I fix this then?

I'm glad you asked...

I suggest making a server-side handler named join which takes the room name as a argument and then the server joins the socket into the room

const express = require("express");
const io = require('socket.io')(express());

io.on("connection", socket => {
  socket.on("join", roomName => {
    socket.join(roomName);
  }
};

Then from you client you can use:

socket.emit("join", "chatroom1");

NOTE: This could potentially be a security problem.

Upvotes: 3

Related Questions