Estbalishing Real-Time Communication
Traditional polling methods for client-server synchronization often result in inefficient bandwidth usage and delayed updates. WebSocket protocol addresses these limitations by enabling full-duplex communication between browsers and servers.
WebSocket Protocol Fundamentals
Core Characteristics
- Bidirectional communication channel
- Persistent connection after initial handshake
- Lower latency compared to HTTP polling
Connection Establishment Process
- Client initiates with SYN packet (SYN_SENT state)
- Server responds with SYN+ACK (SYN_RECV state)
- Client sends ACK confirmation (ESTABLISHED state)
Connection Termination Process
- Initiator sends FIN packet (FIN_WAIT_1 state)
- Receiver acknowledges with ACK (CLOSE_WAIT state)
- Receiver sends FIN (LAST_ACK state)
- Initiator confirms with final ACK (CLOSED state)
Implementation Example: Reservation System
Client-Side Connection Setup
const socketConnection = new WebSocket('ws://server-address:8010/ws-endpoint');
socketConnection.onopen = () => {
console.log('Connection established');
initiateHeartbeat();
};
socketConnection.onmessage = (event) => {
if (event.data === 'ping') {
socketConnection.send('pong');
} else {
processReservationData(JSON.parse(event.data));
}
};
function initiateHeartbeat() {
setInterval(() => {
socketConnection.send('ping');
}, 10000);
}
Server-Side Implementation (Java)
@ServerEndpoint("/ws-endpoint/{deviceId}")
public class RealTimeEndpoint {
private static Map<String, Session> activeSessions = new ConcurrentHashMap<>();
@OnOpen
public void onConnect(Session session, @PathParam("deviceId") String deviceId) {
activeSessions.put(deviceId, session);
sendInitialData(deviceId);
}
private void sendInitialData(String deviceId) {
Session target = activeSessions.get(deviceId);
if (target != null && target.isOpen()) {
List<Reservation> reservations = fetchReservations();
target.getAsyncRemote().sendText(convertToJson(reservations));
}
}
@OnMessage
public void onMessage(String message, Session session) {
if ("ping".equals(message)) {
session.getAsyncRemote().sendText("pong");
}
}
@OnClose
public void onDisconnect(@PathParam("deviceId") String deviceId) {
activeSessions.remove(deviceId);
updateDeviceStatus(deviceId, OFFLINE);
}
}
Connection Monitoring with Heartbeat
- Regular ping-pong messages between client and server
- Connection considered lost if no response within timeout period
- Automatic reconnection attempts when failure detected
- Status tracking through periodic updates