How to point a WebSocket to the current server

后端 未结 1 1660
情歌与酒
情歌与酒 2021-02-03 18:33

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({ ur         


        
相关标签:
1条回答
  • 2021-02-03 19:08

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

    0 讨论(0)
提交回复
热议问题