javascript 如何将 WebSocket 指向当前服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16090530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:14:16  来源:igfitidea点击:

How to point a WebSocket to the current server

javascriptajaxwebsocket

提问by Twinone

I have a Jetty 8 server running (hopefully soon with websockets).

我有一个 Jetty 8 服务器正在运行(希望很快可以使用 websockets)。

If I want to send some data to the server with an ajax call, I can do this:

如果我想通过 ajax 调用向服务器发送一些数据,我可以这样做:

$.ajax({ url: "ajax?a=getSomeData" });

In this scenario, if I connect to my server at 192.168.1.100, the real url where it will get the data from, will be 192.168.1.100/ajax?a=getSomeData, but if I connect to another server running the same software at 192.168.1.200, the url will be 192.168.1.200/ajax?a=getSomeData.

在这种情况下,如果我连接到我的服务器192.168.1.100,它将从中获取数据的真实 url 将是192.168.1.100/ajax?a=getSomeData,但如果我连接到另一台运行相同软件的服务器192.168.1.200,该 url 将是192.168.1.200/ajax?a=getSomeData

But if I want to accomplish the same thing using WebSockets, I cannot find how to do it:

但是如果我想使用 WebSockets 完成同样的事情,我找不到如何去做:

var socket = new WebSocket('ws://www.example.com/');

Works. But I want something like a relative url:

作品。但我想要一个相对网址之类的东西:

var socket = new WebSocket('ws://sockets?a=getSomeData');

So that - like the ajax request - if I were connecting to my server at 192.168.1.100, the url will be 192.168.1.100/sockets?a=getSomeData, and if I connect to 192.168.1.200, the url will be 192.168.1.200/sockets?a=getSomeData.

这样 - 就像 ajax 请求一样 - 如果我连接到我的服务器192.168.1.100,则 url 将是192.168.1.100/sockets?a=getSomeData,如果我连接到192.168.1.200,则 url 将是192.168.1.200/sockets?a=getSomeData.

How can I accomplish this?

我怎样才能做到这一点?

回答by Pointy

Just build the URL yourself:

只需自己构建 URL:

var socket = new WebSocket("ws://" + location.host + "/whatever");

The locationobject is a property of the windowobject, and is therefore globally available.

location对象是一个属性window对象,并且因此是全局可用的。

To get only the host without the port, use location.hostnameinstead. If the websocket server listens on another port for example.

要仅获取没有端口的主机,请location.hostname改用。例如,如果 websocket 服务器侦听另一个端口。

You can also inspect location.protocolto know if you should connect to wss(when httpsis used) or ws(when httpis used).

您还可以检查location.protocol以了解是否应该连接到wss(何时https使用)或ws(何时http使用)。