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?
All you have to do is call the WebSocket constructor and pass in the URL of your server. // Create a new WebSocket. var socket = new WebSocket('ws://echo.websocket.org'); Once the connection has been established, the open event will be fired on your Web Socket instance.
In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.
Port Forwarding is only needed if one client wants to directly connect to the other client. But if all of your websocket messages are being relayed through a public server, then Port Forwarding is not needed.
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).
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