With websockets, is there a place for AJAX?

2019-03-27 05:53发布

I'm currently building a realtime application using Node. I'm using socket.io to power my real-time interactions, but have jQuery loaded, so I have AJAX available to me. I initially used socket.io for all my communication between the server and client.

I'm starting to think that AJAX might be better suited for certain cases like doing RESTful transactions asynchronously, because I don't have to write a separate message case in my socket to handle each new transaction as well as write the RESTful routing.

I'm wondering if I am on to something or if its best to use sockets for performance or something else I'm not thinking about.

Thanks! Matt Mueller

2条回答
何必那么认真
2楼-- · 2019-03-27 06:01

Those are two completely different technologies and could be used together: with AJAX the request is initiated by the client, while with WebSockets the request is initiated by the server in order to push some data to the client.

查看更多
疯言疯语
3楼-- · 2019-03-27 06:22

Yes, WebSockets (RFC 6455) and Ajax are quite different and serve different purposes.

As you say, with Ajax you can do RESTful requests. This means that you can take advantage of existing HTTP-infrastructure like e.g. proxies to cache requests and use conditional get requests. Ajax request may be quite heavy-weight since every Ajax request contains HTTP headers and include cookies.

WebSockets is designed for low latency bi-directional communication. By design, WebSockets has very little overhead in each message. E.g. WebSockets messages doesn't have to include any HTTP Headers, and may in future be used for VoIP and streaming in both directions.

Another difference is that Ajax can be used with stateless servers. E.g. if you have your web load balanced with multiple servers, any server can handle an Ajax request, even after reboot (or upgrade). Websocket's are "connected" and use a stateful server, so it may be harder to use multiple servers with it.

There is also Server Sent Events, that are similar to WebSockets, in that the server can push data to the client (which can't be done with Ajax without hacks (e.g. comet)), and it can also handle automatic reconnections. But it's only for messages in one direction (server to client). See HTML5 Server-Side Event: EventSource vs. wrapped WebSocket.

查看更多
登录 后发表回答