在Java中,我們可以使用Java API for WebSocket (JSR 356)來處理WebSocket連接。以下是一個簡單的示例,展示了如何使用Java Servlet API創建一個WebSocket端點來處理客戶端連接。
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
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 = "/my-websocket", configurator = MyWebSocketConfigurator.class)
public class MyWebSocketEndpoint {
private static Set<Session> sessions = 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 {
// 可以在這里設置端點的屬性,如果需要的話
}
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<Class<?>> 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
方法將被調用,并將消息廣播給所有連接的客戶端。