WebSocket: Evolution, Mechanism, Implementation, and Real‑World Case Study
This article explains the origins and standards of WebSocket, compares its full‑duplex communication model with traditional HTTP, details server‑side and client‑side APIs with Java and JavaScript code examples, and presents a practical case study of real‑time device tracking using Tomcat.
WebSocket: Past and Present
Web applications that require high concurrency and real‑time interaction, such as financial tickers, navigation, and social messaging, cannot rely on the classic request‑response model; traditional solutions like polling or Flash are inefficient or obsolete, leading to the emergence of the HTML5‑based WebSocket protocol.
WebSocket Mechanism
WebSocket establishes a full‑duplex TCP connection after an HTTP‑like handshake, allowing both client and server to send messages at any time without repeatedly opening new connections, thus saving bandwidth and improving latency.
Bidirectional communication similar to a raw socket.
Handshake required before data exchange.
Server‑Side API (Java)
Modern application servers implement the JSR‑356 WebSocket API (javax.websocket.*). An endpoint can be declared with @ServerEndpoint and lifecycle callbacks handle connection events.
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
// ...
}
@OnMessage
public String onMessage(String message) {
// ...
return "echo";
}
@Message(maxMessageSize=6)
public void receiveMessage(String s) {
// ...
}
@OnError
public void onError(Throwable t) {
// ...
}
@OnClose
public void onClose(Session session, CloseReason reason) {
// ...
}
}For older Tomcat versions (7.0.3x) a custom API is required:
public class EchoServlet extends WebSocketServlet {
@Override
protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) {
return new MessageInbound() {
// ...
};
}
protected void onBinaryMessage(ByteBuffer buffer) throws IOException {
// ...
}
protected void onTextMessage(CharBuffer buffer) throws IOException {
getWsOutbound().writeTextMessage(buffer);
}
}Client‑Side API (JavaScript)
All major browsers support the standard WebSocket JavaScript API. A typical usage pattern creates a WebSocket object, registers callbacks, and exchanges JSON messages.
var ws = new WebSocket("ws://echo.websocket.org");
ws.onopen = function(){ ws.send("Test!"); };
ws.onmessage = function(evt){ console.log(evt.data); ws.close(); };
ws.onclose = function(){ console.log("WebSocketClosed!"); };
ws.onerror = function(){ console.log("WebSocketError!"); };Case Study: Real‑Time Device Monitoring
A mobile device manufacturer needed instant location updates from thousands of Android/iOS devices (type A) to management consoles (type B). Using WebSocket, each device opens a persistent connection; the server pushes position changes and status events to the corresponding console without polling.
The server runs on Tomcat 7.0.33 with a custom WebSocketServlet (WebSocketDeviceServlet) that creates a WebSocketDeviceInbound instance for each client. A connection pool ( WebSocketDeviceInboundPool) tracks all active sessions, processes incoming JSON events, and forwards relevant updates to grouped B‑devices.
public class WebSocketDeviceServlet extends org.apache.catalina.websocket.WebSocketServlet {
@Override
protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) {
WebSocketDeviceInbound inbound = new WebSocketDeviceInbound(request);
WebSocketDeviceInboundPool.addMessageInbound(inbound);
return inbound;
}
} public class WebSocketDeviceInbound extends MessageInbound {
private final HttpServletRequest request;
private DeviceAccount connectedDevice;
// constructor obtains device info from session or DB
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
WebSocketDeviceInboundPool.processTextMessage(this, message.toString());
}
public void sendMessage(BaseEvent event) {
String json = JSON.toJSONString(event);
this.getWsOutbound().writeTextMessage(CharBuffer.wrap(json));
}
}The pool provides utility methods to add/remove connections, retrieve online devices, and broadcast or target messages based on device groups.
public class WebSocketDeviceInboundPool {
private static final List<WebSocketDeviceInbound> connections = new ArrayList<>();
public static void addMessageInbound(WebSocketDeviceInbound inbound) {
connections.add(inbound);
}
public static void removeMessageInbound(WebSocketDeviceInbound inbound) {
connections.remove(inbound);
}
public static void sendMessageToAllDevices(BaseEvent event) {
for (WebSocketDeviceInbound client : connections) {
client.sendMessage(event);
}
}
// ... other helper methods ...
}Client Script (websocket.js)
The JavaScript client wraps the native WebSocket API, handles login, receives events, updates a map, and sends JSON messages back to the server.
var websocket = window.WebSocket || window.MozWebSocket;
function initWebSocket(url) {
if (window.WebSocket) {
websocket = new WebSocket(encodeURI(url));
websocket.onopen = doOpen;
websocket.onmessage = doMessage;
websocket.onerror = doError;
websocket.onclose = doClose;
}
}
function doMessage(message) {
var event = $.parseJSON(message.data);
// process event types, update UI, etc.
}Conclusion
The article provides a comprehensive overview of WebSocket’s history, protocol details, server‑side Java APIs, client‑side JavaScript usage, and a concrete deployment scenario, offering developers a solid reference for building real‑time, high‑concurrency web applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Art of Distributed System Architecture Design
Introductions to large-scale distributed system architectures; insights and knowledge sharing on large-scale internet system architecture; front-end web architecture overviews; practical tips and experiences with PHP, JavaScript, Erlang, C/C++ and other languages in large-scale internet system development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
