WebSocket in Java: Java-WebSocket Library
In modern web development, the need for real-time two-way communication is becoming increasingly relevant. Chat applications, online games, stock quotes, notifications — all of these require instant data transfer between client and server. For Java, one of the most popular and reliable implementations of the WebSocket protocol is the Java-WebSocket library (also known as nv-websocket-client).
In this article, we will take a detailed look at how to use Java-WebSocket to create server and client applications, provide code examples, and discuss best practices.
What is Java-WebSocket?
Java-WebSocket is a lightweight, powerful open-source library that implements the WebSocket protocol (RFC 6455). It allows Java developers to easily create both WebSocket servers and WebSocket clients without having to delve into the low-level details of the protocol.
Key features of the library:
- Full support for both server-side and client-side WebSocket.
- Support for WSS (WebSocket Secure) via SSL/TLS.
- Automatic reconnection upon connection loss.
- Handling of fragmented messages.
- Support for custom extensions.
- Simple event-based API (onOpen, onMessage, onClose, onError).
Installation and Setup
To use the library, add the dependency to your pom.xml (Maven):
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.5.4</version></dependency>If you are using Gradle:
implementation 'org.java-websocket:Java-WebSocket:1.5.4'Creating a WebSocket Server
Let's look at a simple example of a WebSocket server that receives messages and sends them back to all connected clients (echo server):
import org.java_websocket.WebSocket;import org.java_websocket.handshake.ClientHandshake;import org.java_websocket.server.WebSocketServer;import java.net.InetSocketAddress;import java.util.Set;
public class EchoServer extends WebSocketServer {
public EchoServer(int port) { super(new InetSocketAddress(port)); }
@Override public void onOpen(WebSocket conn, ClientHandshake handshake) { System.out.println("New connection: " + conn.getRemoteSocketAddress()); }
@Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { System.out.println("Disconnection: " + conn.getRemoteSocketAddress() + " (" + reason + ")"); }
@Override public void onMessage(WebSocket conn, String message) { System.out.println("Received message: " + message); // Send the message back to all clients Set<WebSocket> connections = getConnections(); for (WebSocket client : connections) { client.send("Echo: " + message); } }
@Override public void onError(WebSocket conn, Exception ex) { System.err.println("Error: " + ex.getMessage()); if (conn != null) { conn.close(); } }
@Override public void onStart() { System.out.println("Server started on port " + getPort()); }
public static void main(String[] args) { int port = 8887; EchoServer server = new EchoServer(port); server.start(); }}This server runs on port 8887 and, upon receiving any message, sends it back to all connected clients with the prefix "Echo:".
Creating a WebSocket Client
Now let's write a client that connects to our server
Also in library
Reactive Programming in C++: RxCpp and Boost.Signals2 Libraries
Puppeteer for JavaScript (Node.js): Complete Guide with Examples
Swift Application Monitoring: Libraries for iOS and macOS
Elasticsearch client for Rust: overview of the elasticsearch-rs library