在Java中实现WebSocket通信,你可以使用Java API for WebSocket (JSR 356) 或者一些流行的库,如Spring Boot和Tyrus。下面是一个简单的示例,展示了如何使用Java API for WebSocket创建一个基本的WebSocket服务器。
- 首先,确保你的项目中包含了Java WebSocket API。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:
javax.websocket javax.websocket-api 1.1
- 创建一个WebSocket服务器端点类:
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 = "https://www.yisu.com/websocket") public class WebSocketServer { private static Setsessions = 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()); } } } }
- 创建一个WebSocket服务器类,用于启动服务器并注册WebSocket端点:
import javax.websocket.server.Server; import java.util.HashSet; import java.util.Set; public class WebSocketServer { public static void main(String[] args) { Set> 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的客户端库来测试这个服务器。