Client-side socket.io without a node.js server

前端 未结 3 1661
走了就别回头了
走了就别回头了 2021-01-17 14:31

To use socket.io on the client side, usually we start a node.js server and go like this:


         


        
3条回答
  •  不思量自难忘°
    2021-01-17 15:00

    You obviously can host the socket.io client library anywhere and pull it in to a page. However, it will almost certainly not work with your Java-based server.

    To understand why, you need to understand what socket.io is really doing behind the scenes; the client library is only a small part of it.

    Socket.io actually defines and implements its own protocol for realtime communication between a browser and a server. It does so in a way that supports multiple transports: if—for example—a user's browser or proxy doesn't support WebSockets, it can fall back to long polling.

    What the socket.io client actually does is:

    1. Makes a XHR GET request for /socket.io/1. The server responds with a session ID, configured timeouts, and supported transports.
    2. The client chooses the best transport that the user browser supports. In modern browsers, it will use WebSockets.
    3. If WebSockets are supported, it creates a new WebSocket to initiate a WebSocket connection (HTTP GET with Upgrade: websocket header) to a special URL – /socket.io/1/websocket/.
    4. If WebSockets aren't supported by the browser or fail to connect (there are lots of intermediaries in the wild like proxies, filters, network security devices, and so forth that don't support WebSocket requests), the library falls back to XHR long polling, and makes a XHR request to /socket.io/1/xhr-polling/. The server does not respond to the request until a new message is available or a timeout is reached, at which point the client repeats the XHR request.

    Socket.io's server component handles the other end of that mess. It handles all the URLs under /socket.io/, setting up sessions, parsing WebSocket upgrades, actually sending messages, and a bunch of other bookkeeping.

    Without all of the services provided by the socket.io server, the client library is pretty useless. It will just make a XHR request to a URL that doesn't exist on your server.

    My guess is that your Java-based server just implements the WebSockets protocol. You can connect directly to it using the browser-provided WebSocket APIs.

    It is possible that your server does implement the socket.io protocol – there are a few abandoned Java projects to do that – but that's unlikely. Talk with the developer of your server to find out exactly how he's implemented a "socket server."

提交回复
热议问题