A Java WebSocket server is a software program written in the Java programming language that enables bidirectional communication between clients and servers over the WebSocket protocol.
The WebSocket protocol provides a way for web browsers and servers to communicate using a single connection, allowing real-time data transfer without the overhead of HTTP requests.
To create a Java WebSocket server, you can use one of the many available libraries such as:
- Jetty - A lightweight and highly scalable server that supports both client and server-side WebSockets.
- Tomcat - A popular open-source server that provides support for WebSockets through its native API.
- Netty - A high-performance networking library that includes support for WebSockets.
Once you have chosen your library, you can implement your WebSocket server by following these basic steps:
- Create a class that extends the WebSocketHandler or ChannelInboundHandlerAdapter class depending on the chosen library.
- Override the methods to handle different events like connection establishment, incoming messages, disconnection etc.
- Configure and start your server by creating an instance of Server or HttpServer depending on your choice of library.
- Bind your server to a specific port and wait for incoming connections.
Here’s an example implementation of a simple Java WebSocket server using Jetty:
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.*;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
@WebSocket
public class MyWebSocketHandler extends WebSocketHandler {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyWebSocket.class);
}
}
@WebSocket
public class MyWebSocket {
@OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("Client connected: " + session.getRemoteAddress().getHostString());
}
@OnWebSocketMessage
public void onMessage(Session session, String message) {
System.out.println("Received message: " + message);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("Closed with status " + statusCode + ", reason: " + reason);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.setHandler(new MyWebSocketHandler());
server.start();
server.join();
}
}
In this example, we define a WebSocket handler that extends the Jetty WebSocketHandler class and registers a WebSocket endpoint using the factory method. We also define a separate WebSocket class that handles events like connection establishment, incoming messages and disconnection.
To start the server, we create an instance of the Jetty Server class and set our custom WebSocket handler as the server’s handler before starting it on port 8080.




