2

I have a page that open a websocket connection back to the server. The websocket server is ws://127.0.0.1:5000/ws when in development and ws://www.mymachine.com/ws when deployed to production. Is there a short hand for this, so I don't have to re-write this URI manually from 127.0.0.1:5000 to www.mymachine.com when I deploy?

I've tried ws://ws but it doesn't work. I'm trying to get the same behavior as a normal url where you can use /index and it will go to 127.0.0.1:5000/index or www.mymachine.com/index depending on where it is running.

nickponline
  • 25,354
  • 32
  • 99
  • 167

2 Answers2

2

I had a similar problem. I solved using:

 var uri= window.location.host + window.location.pathname + 'ws'
  if (window.location.protocol === 'http:') {
    mysocket.connect('ws://' + uri);
  } else {
    mysocket.connect('wss://' +uri);
  }
Gabriele Santomaggio
  • 21,656
  • 4
  • 52
  • 52
0

Apart from 1 simple variable in the top of your (initialization-)script, you could look into the File API - A URL for Blob and File reference:

This specification defines a scheme with URLs of the sort:
blob:550e8400-e29b-41d4-a716-446655440000#aboutABBA.

These are stored in an URL store and browsers should even have their own mini HTTP-server aboard so one can use these urls in css, img src and even XMLHttpRequest.

Your initialization-script would then use an if/else to build your url-object and put it in the store.
Some more info is in this answer. (Besides, backwards compatibility is kind of not your problem when using web-sockets..)

Hope this springs some idea's to your mind.

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80