Part 1 – How server sends notification to client? Polling and Server Sent Events
https://www.onlyfullstack.com/polling-and-server-sent-events/
What is WebSocket?
Why WebSocket?
WebSockets enable the server and client to send messages to each other at any time, after a connection is established, without an explicit request by one or the other. This is in contrast to HTTP, which is traditionally associated with the challenge-response principle — where to get data one has to explicitly request it. In more technical terms, WebSockets enable a full-duplex connection between the client and the server.
In a challenge-response system there is no way for clients to know when new data is available for them (except by asking the server periodically —polling or long polling), with Websockets the server can push new data at any time which makes them the better candidate for “real-time” applications.
Polling vs Server Sent Events vs WebSocket
1. Message Flow
Polling :
Server Sent Events :
WebSockets :
2. Communication Techniques
Polling : request → response. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.
Server Sent Events : request → wait → response. Creates a connection to the server, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server.
WebSockets : client ↔ server. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time.
3. Communication Type
Polling : Supports unidirectional communication where only server can send the data on clients request.
4. Protocol
Polling : Uses HTTP protocol for the communication.
5. Usage
Polling : Avoid polling as its an old technique to get the data from the server.
– Real-time news coverage of an important event (posting links, tweets, and images)
– A live Github / Twitter dashboard wall fed by Twitter’s streaming API
– A monitor for server statistics like uptime, health, and running processes.
WebSocket : WebSockets can be used when we need bidirectional communication in between client and server. Some of examples are as below –
Download the source code of WebSocket tutorial from below git repository :
websocket-with-spring-boot-and-angular-6
Let’s go to our next tutorial where we will discuss below points :
– Spring Boot + STOMP + WebSocket Backend
– Angular 6 + StompJs + WebSocket Frontend