如何将WebSocket指向当前服务器 [英] How to point a WebSocket to the current server

查看:95
本文介绍了如何将WebSocket指向当前服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在运行的Jetty 8服务器(希望很快会使用websockets).

如果我想通过ajax调用将一些数据发送到服务器,则可以执行以下操作:

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

在这种情况下,如果我通过 192.168.1.100 连接到服务器,则从中获取数据的真实网址将是 192.168.1.100/ajax?a=getSomeData,但如果我连接到另一台在 192.168.1.200 上运行相同软件的服务器,则该URL将为 192.168.1.200/ajax?a=getSomeData ./p>

但是,如果我想使用WebSockets完成相同的操作,我将找不到执行该操作的方法:

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

工作.但我想要类似的相对网址:

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

因此,就像ajax请求一样,如果我以 192.168.1.100 连接到我的服务器,则URL将为 192.168.1.100/sockets?a=getSomeData ,如果我连接到 192.168.1.200 ,则网址将为 192.168.1.200/sockets?a=getSomeData .

我该怎么做?

解决方案

只需自己构建URL:

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

location 对象是 window 对象的属性,因此是全局可用的.

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

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

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

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

$.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.

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

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.

How can I accomplish this?

解决方案

Just build the URL yourself:

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

The location object is a property of the window object, and is therefore globally available.

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

You can also inspect location.protocol to know if you should connect to wss (when https is used) or ws (when http is used).

这篇关于如何将WebSocket指向当前服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆