ngx-socket-io icon indicating copy to clipboard operation
ngx-socket-io copied to clipboard

How to stop auto web-socket connection and do it manually

Open aleixfargas opened this issue 3 years ago • 4 comments

How to prevent Socket to autoConnect to socket and do it manually?

In my application, I only need the socket connection when user is logged in, and it is connecting always, and we suspect that it may be affecting on page performance loading time.

Is it possible. Thank you

aleixfargas avatar Jul 29 '22 09:07 aleixfargas

@aleixfargas i need todo the same. What I had luckily a static injector. You can check this stackoverflow. Then you can inject the service statically like so:

@Injectable({providedIn: 'root'})
export class SocketOne extends Socket {
  constructor() {
    super({ url: 'http://url_one:portOne', options: {} });
  }
}

Do not forget the providedIn. Now you can use it anywhere ondemand...like this

import {AppInjector} from './app-injector';
const SocketOneSvc = AppInjector.get(SocketOne);

dotnetdreamer avatar Aug 15 '22 16:08 dotnetdreamer

@dotnetdreamer Thank you. We finally kept it as is, so the static injector did not work correctly in our case. Anyway, it would be a great feature for this plugin to allow this by default, don't you think? :)

aleixfargas avatar Nov 29 '22 10:11 aleixfargas

How to prevent Socket to autoConnect to socket and do it manually?

In my application, I only need the socket connection when user is logged in, and it is connecting always, and we suspect that it may be affecting on page performance loading time.

Is it possible. Thank you

It is possibile! Just put in options: { autoConnect: false }

And connect to the socket endpoint manualy!

constructor() {
   super({ url: environment.sockApi+ '/customer', options: { autoConnect: false } });
 }

// Send manualy connection
 sendConnect() {
   if (this.ioSocket.connected) {
     return;
   } else {
     this.ioSocket.connect();
   }
 }

// Disconnect Manuly
 sendDisconnect() {
   this.ioSocket.disconnect();
 }

Ruslancic avatar May 11 '23 19:05 Ruslancic

I needed to change the uri+namespace+auth outside of the constructor, I came up with this ugly workround.

export class MySockeService extends Socket {
  auth: any
  constructor() {
    const auth = {}
    super({ url: '/',  options: { transports: ['websocket'], autoConnect: false, auth } })
    this.auth = auth;
  }
  
  later_change_the(uri: string) {
    const wsurl = new URL(uri)
    const { io } = this.ioSocket

    io.uri = wsurl.toString()
    io.opts.hostname = wsurl.host
    io.opts.port = wsurl.port
    io.opts.path = wsurl.pathname + 'optional_namespace'
    this.auth['api-key'] = 'because it would be too simple'

    this.ioSocket.connect()
  }
}

vincent avatar Feb 10 '24 23:02 vincent