在Java中,我们可以使用Java API for WebSocket (JSR 356)来处理WebSocket连接。以下是一个简单的示例,展示了如何使用Java Servlet API创建一个WebSocket端点来处理客户端连接。
- 首先,确保你的项目已经包含了Java WebSocket库。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:
javax.websocket javax.websocket-api 1.1
- 创建一个WebSocket端点类,例如
MyWebSocketEndpoint.java
:
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/my-websocket", configurator = MyWebSocketConfigurator.class) public class MyWebSocketEndpoint { private static Setsessions = Collections.synchronizedSet(new HashSet<>()); @OnOpen public void onOpen(Session session) { sessions.add(session); System.out.println("New connection established: " + session.getId()); } @OnMessage public void onMessage(String message, Session session) { System.out.println("Received message from " + session.getId() + ": " + message); broadcastMessage(message); } @OnClose public void onClose(Session session) { sessions.remove(session); System.out.println("Connection closed: " + session.getId()); } @OnError public void onError(Throwable error) { System.err.println("Error occurred: " + error.getMessage()); } private void broadcastMessage(String message) { for (Session session : sessions) { if (session.isOpen()) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { System.err.println("Error sending message to session " + session.getId() + ": " + e.getMessage()); } } } } }
- 创建一个配置类,例如
MyWebSocketConfigurator.java
,用于设置WebSocket端点的属性(如果需要):
import javax.websocket.server.ServerEndpointConfig; @ServerEndpointConfig(configurator = MyWebSocketConfigurator.class) public class MyWebSocketConfigurator extends ServerEndpointConfig.Configurator { // 可以在这里设置端点的属性,如果需要的话 }
- 创建一个WebSocket服务器,例如
WebSocketServer.java
:
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(MyWebSocketEndpoint.class); Server server = new Server("localhost", 8080, "/my-websocket", classes); try { server.start(); System.out.println("WebSocket server started on port 8080"); } catch (Exception e) { System.err.println("Error starting WebSocket server: " + e.getMessage()); } } }
现在,当你运行WebSocketServer
类时,它将启动一个WebSocket服务器,监听端口8080上的/my-websocket
路径。当客户端连接到这个端点时,MyWebSocketEndpoint
类中的onOpen
方法将被调用,并将客户端会话添加到sessions
集合中。当客户端发送消息时,onMessage
方法将被调用,并将消息广播给所有连接的客户端。