Implementing Real-Time Messaging with WebSocket Technology

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

  1. Client initiates with SYN packet (SYN_SENT state)
  2. Server responds with SYN+ACK (SYN_RECV state)
  3. Client sends ACK confirmation (ESTABLISHED state)

Connection Termination Process

  1. Initiator sends FIN packet (FIN_WAIT_1 state)
  2. Receiver acknowledges with ACK (CLOSE_WAIT state)
  3. Receiver sends FIN (LAST_ACK state)
  4. 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

  1. Regular ping-pong messages between client and server
  2. Connection considered lost if no response within timeout period
  3. Automatic reconnection attempts when failure detected
  4. Status tracking through periodic updates

Tags: WebSocket real-time communication java javascript network protocols

Posted on Wed, 21 Oct 2026 16:49:22 +0000 by andrewmcgibbon