在Java中实现WebSocket通信,你可以使用Java API for WebSocket (JSR 356) 或者一些流行的库,如Spring Boot和Tyrus。下面是一个简单的示例,展示了如何使用Java API for WebSocket创建一个基本的WebSocket服务器。
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@ServerEndpoint(value = "/websocket")
public class WebSocketServer {
private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("New client connected: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message from client " + session.getId() + ": " + message);
broadcastMessage("Message from server: " + message);
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("Client disconnected: " + session.getId());
}
@OnError
public void onError(Exception error) {
System.err.println("Error in WebSocket server: " + error.getMessage());
}
private void broadcastMessage(String message) {
for (Session session : sessions) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
System.err.println("Error sending message to client: " + e.getMessage());
}
}
}
}
import javax.websocket.server.Server;
import java.util.HashSet;
import java.util.Set;
public class WebSocketServer {
public static void main(String[] args) {
Set<Class<?>> classes = new HashSet<>();
classes.add(WebSocketServer.class);
Server server = new Server("localhost", 8080, classes);
try {
server.start();
System.out.println("WebSocket server started on port 8080");
server.wait();
} catch (Exception e) {
System.err.println("Error starting WebSocket server: " + e.getMessage());
}
}
}
现在,当你启动WebSocket服务器并访问ws://localhost:8080/websocket
时,你将能够与服务器进行实时通信。你可以使用任何支持WebSocket的客户端库来测试这个服务器。