2

In my project, i have some sockets which needs to be authenticated and some sockets which are not containing the auth-token.

const socket = require('socket.io');
let server = require('http').createServer(app);


require('./config/authSockets')(socket(server));

require('./config/sockets')(socket(server));

I have created separate files for this scenario that in authSockets, first it should check that if socket has the token then it'll open the connection only and emit those sockets. and the next file which is ./config/sockets this file should run everytime and it donot require the socket. but my code isn't working, its always only accept the second file.

  • 1
    Please show us the code so we can see what you're trying to do in those last two lines of code. As best I know, you can't bind two socket.io servers to the same web server and expect both of them to get all the socket.io messages. – jfriend00 Aug 22 '20 at 00:31
  • @jfriend00 So what would be the best possiblle solution to implement that sockets with and without authentication ? Here is my authsockets and sockets . https://gist.github.com/Talha089/75bcbd5133aae9052e3285a8b2e0c5ac https://gist.github.com/Talha089/2e0f7793d18776ad384a1ffa80c5a046 – Talha Javaid Malik Aug 23 '20 at 07:26
  • 1
    I would suggest you use socket.io namespaces and you require authentication for one of the namespaces and not the other. Both namespaces are served by the same socket.io server, but you can handle each namespace differently (requiring auth for one, but not the other). – jfriend00 Aug 23 '20 at 08:03
  • @jfriend00 i have used the namespaces and it works fine if i add them in one file, i want to place them in different files so my project structure remains mature. If I add them in other files it connects the second socket: Authenticated or simple. – Talha Javaid Malik Aug 24 '20 at 21:23

1 Answers1

0

I would suggest you use socket.io namespaces and you require authentication for one of the namespaces and not the other. Both namespaces are served by the same socket.io server, but you can handle each namespace differently (requiring auth for one, but not the other). This is a perfect application for socket.io namespaces (two separate purposes sharing the same socket.io server and client connection).

Working socket.io across two files is done by importing and exporting the right things. I've answered questions like that many times before here, but to help you specifically, I'd have to see your actual code (pasted into your question) to know exactly what module sharing solution to suggest.

jfriend00
  • 683,504
  • 96
  • 985
  • 979