A Practical Java WebSocket Client Wrapper: Design, Features, and Demo
This article introduces a reusable Java WebSocket client wrapper that adds convenient date handling, message logging, configurable constants, and performance‑testing utilities, explains its implementation details with full source code, and provides a simple demo showing connection, messaging, and graceful shutdown.
Overview
The WebSocketFunClient class is a lightweight wrapper around org.java_websocket.client.WebSocketClient. It is designed for rapid WebSocket protocol testing and performance measurement by providing convenient factory methods, connection‑retry logic, logging, and a bounded message buffer.
Key Features
Factory methods getInstance(String url) and getInstance(String url, String cname) create client instances with a unique name (cname) for easier identification in logs.
Automatic connection retry: after connect() the client polls ReadyState.OPEN and retries up to SocketConstant.MAX_WATI_TIMES with a pause of SocketConstant.WAIT_INTERVAL milliseconds.
Thread‑safe bounded message buffer: a LinkedList<String> stores the most recent messages, capped by SocketConstant.MAX_MSG_SIZE. Older entries are discarded automatically.
Utility send overloads for raw strings, custom Charset, JSON objects ( com.alibaba.fastjson.JSONObject), and custom beans ( AbstractBean).
Static collection Vector<WebSocketFunClient> socketClients tracks all created instances, enabling bulk shutdown via closeAll().
Configuration Constants
The companion class SocketConstant (not reproduced here) defines static values used throughout the client: MAX_MSG_SIZE – maximum number of messages retained in the buffer. MAX_WATI_TIMES – maximum number of connection‑retry attempts. WAIT_INTERVAL – sleep interval (ms) between retry attempts.
Core Implementation Details
Important overridden callbacks: onOpen(ServerHandshake handshakedata) – logs handshake fields. onMessage(String message) – stores the message in the bounded buffer and logs it. onClose(int code, String reason, boolean remote) – logs closure details. onError(Exception e) – logs exceptions.
Additional methods: saveMsg(String msg) – synchronized insertion into the bounded buffer. close() – logs a warning, closes the socket, and removes the instance from socketClients. closeAll() – iterates over socketClients, closes any open connections, clears the collection, and logs the operation. clone() – creates a new client with the same URL but a different random suffix for cname, useful for concurrent performance tests.
Usage Example
public static void main(String[] args) {
WebSocketFunClient client = WebSocketFunClient.getInstance("ws://127.0.0.1:8080/ws/fun");
client.connect();
client.send("FunTester");
// wait for messages or perform further actions
Thread.sleep(10000);
client.close();
}Sample Console Output
INFO FunTesterkgbn 正在建立socket连接...
INFO 握手信息key: Connection ,value: upgrade
INFO 握手信息key: Date ,value: Mon, 30 Nov 2020 09:16:30 GMT
INFO 握手信息key: Sec-WebSocket-Accept ,value: yQj8IZx/STCzhcWY0ovQ98hxI8o=
INFO 握手信息key: Upgrade ,value: websocket
INFO FunTesterkgbn收到: 世界喊话器 用户:fun已经上线了!
INFO FunTesterkgbn 连接成功!
INFO FunTesterkgbn收到: 世界喊话器 fun:FunTester
WARN FunTesterkgbn:socket连接关闭!
INFO FunTesterkgbn socket 连接关闭,URL: ws://127.0.0.1:8080/ws/fun ,code码:1000,原因:,是否由远程服务关闭:falseThe source code, including the WebSocketFunClient implementation and the SocketConstant configuration class, is version‑controlled in a Git repository. Clone the repository to obtain the latest updates and integrate the client into your own WebSocket testing framework.
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.
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.
