如何构造相对于页面 URI 的 WebSocket URI? [英] How to construct a WebSocket URI relative to the page URI?

查看:33
本文介绍了如何构造相对于页面 URI 的 WebSocket URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在浏览器端构造一个相对于页面 URI 的 WebSocket URI.说,在我的情况下转换 HTTP URIs 像

I want to construct a WebSocket URI relative to the page URI at the browser side. Say, in my case convert HTTP URIs like

http://example.com:8000/path
https://example.com:8000/path

ws://example.com:8000/path/to/ws
wss://example.com:8000/path/to/ws

我目前正在做的是将前 4 个字母http"替换为ws",并在其后附加/to/ws".有没有更好的办法?

What I'm doing currently is replace the first 4 letters "http" by "ws", and append "/to/ws" to it. Is there any better way for that?

推荐答案

如果您的 Web 服务器支持 WebSockets(或 WebSocket 处理程序模块),那么您可以使用相同的主机和端口,并像您显示的那样更改方案.有许多选项可以同时运行 Web 服务器和 Websocket 服务器/模块.

If your Web server has support for WebSockets (or a WebSocket handler module) then you can use the same host and port and just change the scheme like you are showing. There are many options for running a Web server and Websocket server/module together.

我建议您查看 window.location 全局的各个部分并将它们重新连接在一起,而不是进行盲目的字符串替换.

I would suggest that you look at the individual pieces of the window.location global and join them back together instead of doing blind string substitution.

var loc = window.location, new_uri;
if (loc.protocol === "https:") {
    new_uri = "wss:";
} else {
    new_uri = "ws:";
}
new_uri += "//" + loc.host;
new_uri += loc.pathname + "/to/ws";

请注意,某些 Web 服务器(即基于 Jetty 的服务器)当前使用路径(而不是升级标头)来确定是否应将特定请求传递给 WebSocket 处理程序.因此,您是否可以按照自己想要的方式转换路径可能会受到限制.

Note that some web servers (i.e. Jetty based ones) currently use the path (rather than the upgrade header) to determine whether a specific request should be passed on to the WebSocket handler. So you may be limited in whether you can transform the path in the way you want.

这篇关于如何构造相对于页面 URI 的 WebSocket URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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