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
to
ws://example.com:8000/path/to/ws wss://example.com:8000/path/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?
To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.
WebSocket URIs have the same basic format as HTTP URIs, but with a different URI scheme: ws://hostname:port/path, e.g. ws://example.com/echo or ws://example.net:8080. The path can be used to distinguish the purpose of the connection; however, some servers ignore it.
Creating a WebSocket object The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss:// , although some software may allow you to use the insecure ws:// for local connections. Either a single protocol string or an array of protocol strings.
Following is the API which creates a new WebSocket object. var Socket = new WebSocket(url, [protocal] ); Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.
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.
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With