Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to point a WebSocket to the current server

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?

like image 473
Twinone Avatar asked Apr 18 '13 18:04

Twinone


People also ask

How do I connect to WebSocket server?

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.

How do you handle WebSocket connections?

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.

Do WebSockets port forward?

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.


1 Answers

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

like image 123
Pointy Avatar answered Oct 06 '22 13:10

Pointy