简体   繁体   English

如何为Websocket连接指定主机?

[英]How do I specify the host for a websocket connection?

I have a page that open a websocket connection back to the server. 我有一个页面可以打开与服务器的websocket连接。 The websocket server is ws://127.0.0.1:5000/ws when in development and ws://www.mymachine.com/ws when deployed to production. Websocket服务器在开发中时为ws://127.0.0.1:5000 / ws,在部署到生产环境中时为ws://www.mymachine.com/ws。 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? 这是否有捷径,所以部署时我www.mymachine.com from 127.0.0.1:5000www.mymachine.com手动重写此URI?

I've tried ws://ws but it doesn't work. 我已经尝试过ws://ws但没有用。 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. 我正在尝试获得与普通网址相同的行为,您可以在其中使用/index ,根据其运行位置,它将转到127.0.0.1:5000/index或www.mymachine.com/index。

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);
  }

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: 除了(初始化)脚本顶部的1个简单变量之外,您还可以查看File API-Blob和File引用的URL

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. 这些都存储在一个URL store ,浏览器甚至应该拥有自己的微型HTTP服务器,以便可以在css,img src甚至XMLHttpRequest中使用这些URL。

Your initialization-script would then use an if/else to build your url-object and put it in the store. 然后,您的初始化脚本将使用if / else来构建您的url对象并将其放入存储中。
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. 希望这能使您想到一个主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM