Java websockets examples

Gary 30 Published: 08/05/2024

Java websockets examples

Here are some Java WebSocket examples:

Example 1: Simple Echo Server

In this example, we create a simple WebSocket server that echoes back any messages it receives from clients.

import javax.websocket.*;

import java.io.IOException;

@ServerEndpoint("/echo")

public class EchoServer {

@OnMessage

public void handleMessage(String message, Session session) throws IOException {

session.getBasicRemote().sendText(message);

}

}

Example 2: Chat Application

In this example, we create a simple chat application that allows multiple clients to communicate with each other.

import javax.websocket.*;

import java.io.IOException;

@ServerEndpoint("/chat")

public class ChatServer {

private static final Set sessions = new HashSet<>();

@OnOpen

public void onOpen(Session session) {

sessions.add(session);

}

@OnMessage

public void handleMessage(String message, Session session) throws IOException {

for (Session s : sessions) {

if (!s.equals(session)) {

s.getBasicRemote().sendText(message);

}

}

}

@OnClose

public void onClose(Session session) {

sessions.remove(session);

}

}

Example 3: Broadcasting Messages

In this example, we create a server that can broadcast messages to all connected clients.

import javax.websocket.*;

import java.io.IOException;

@ServerEndpoint("/broadcast")

public class Broadcaster {

private static final Set sessions = new HashSet<>();

@OnOpen

public void onOpen(Session session) {

sessions.add(session);

}

@OnMessage

public void handleMessage(String message, Session session) throws IOException {

for (Session s : sessions) {

s.getBasicRemote().sendText(message);

}

}

@OnClose

public void onClose(Session session) {

sessions.remove(session);

}

}

Example 4: Handling Errors

In this example, we create a server that handles errors by sending an error message to all connected clients.

import javax.websocket.*;

import java.io.IOException;

@ServerEndpoint("/error")

public class ErrorHandler {

private static final Set sessions = new HashSet<>();

@OnOpen

public void onOpen(Session session) {

sessions.add(session);

}

@OnMessage

public void handleMessage(String message, Session session) throws IOException {

try {

// process message

} catch (IOException e) {

sendError(session, e.getMessage());

}

}

@OnClose

public void onClose(Session session) {

sessions.remove(session);

}

private void sendError(Session session, String errorMessage) throws IOException {

session.getBasicRemote().sendText(errorMessage);

}

}

Example 5: Handling Multiple Types of Messages

In this example, we create a server that can handle different types of messages (e.g. text, binary).

import javax.websocket.*;

import java.io.IOException;

import java.util.UUID;

@ServerEndpoint("/multi-type")

public class MultiTypeHandler {

private static final Set sessions = new HashSet<>();

@OnOpen

public void onOpen(Session session) {

sessions.add(session);

}

@OnMessage

public void handleMessage(String message, Session session) throws IOException {

// handle text messages

}

@OnMessageBytes

public void handleBinaryMessage(Bytes message, Session session) throws IOException {

// handle binary messages

}

}

These are just a few examples of how you can use Java WebSockets to create different types of applications. The possibilities are endless!

java websocket example

Here's an example of a simple Java-based WebSocket server using the javax.websocket API and a WebSocket client implemented in JavaScript:

Java WebSocket Server (EchoServer.java)

import javax.websocket.*;

import javax.websocket.server.*;

@ServerEndpoint("/echo")

public class EchoServer {

@OnOpen

public void handleConnection(SESSION session) {

System.out.println("Client connected");

}

@OnMessage

public String receiveTextMessage(String message, SESSION session) {

System.out.println("Received: " + message);

return message;

}

@OnError

public void handleException(Throwable throwable) {

System.out.println("Error occurred: " + throwable.getMessage());

}

@OnClose

public void handleClose(SESSION session) {

System.out.println("Client disconnected");

}

}

JavaScript WebSocket Client (index.html)


WebSocket Example

How it works:

The Java WebSocket server (EchoServer.java) is a simple example that echoes back any messages received from clients. The JavaScript WebSocket client (index.html) establishes a connection to the server and sends a message ("Hello from client!"). The server receives this message and responds with an echo of the original message. The client prints out the response from the server and then sends another message back to the server.

Note: In order for this example to work, you'll need to:

Start a Java-based WebSocket server using a suitable container (e.g., Apache Tomcat or Jetty) with the EchoServer class. Load the JavaScript client (index.html) in a web browser that supports WebSockets (most modern browsers do).

This example demonstrates the basic principles of WebSocket communication: establishing connections, sending messages, and handling disconnections. You can modify this example to build more complex applications or services.

References:

javax.websocket API documentation WebSocket tutorial by Mozilla Developer Network