We're going to cover how to use WebSockets to create real-time web applications with React and Node JS and EC2 Polling issue fix in AWS.
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.
WebSockets convert their HTTP connection to a WebSocket connection. In other words, a WebSocket connection uses HTTP only to do the initial handshake (for authorization and authentication), after which the TCP connection is utilized to send data via its own protocol.
Websocket provide the connection between the client and server. That enable both parties can send messages to each other at any time.
The client make the websocket connection using websocket handshake. websocket handshake is a bridge from HTTP to WebSockets.
The client request an http connection with upgrade header. This header informs to the server the clients want a web socket connection.
The server establish the connection if the server supports the socket protocol. This connection made by sending upgrade header as response.
Now we will implement websocket connection with React and NodeJS server using Socket.IO.
npm i socket.io-client -S
var io = require('socket.io')(http, { path: '/socket.io' });
this.socket = io.connect('http://localhost:8081', { path: '/socket.io' });
This websocket connection working fine with local. Now I like to move it to production. So I've uploaded the server code in AWS Elastic Beanstalk.
The websocket successfully connected in http. But I've faced polling issue in https (SSL port). The web client connects but never upgrades, and just stays in polling mode.
When there is no proper connection between socket server and client, the socket io client package makes frequent http calls to get data from server instead of websocket protocol.
We need to change the proxy header in EC2 to fix this issue. Follow below steps to edit the proxy setting in windows.