在Java中,我們可以使用Java API for WebSocket (JSR 356)來實現WebSocket服務器。要處理WebSocket消息,你需要遵循以下步驟:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
javax.websocket.Endpoint
接口的類,該類將作為WebSocket服務器的端點。在這個類中,你可以重寫onOpen
、onMessage
、onClose
和onError
方法來處理WebSocket連接的生命周期事件和消息。import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MyWebSocketEndpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
System.out.println("WebSocket連接已打開: " + session.getId());
// 添加消息處理器
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String message) {
System.out.println("收到客戶端消息: " + message);
// 處理消息并發送響應
session.getAsyncRemote().sendText("服務器已收到消息: " + message, result -> {
if (result.getException() != null) {
System.out.println("發送響應失敗: " + result.getException());
}
});
}
});
}
@Override
public void onClose(Session session, CloseReason closeReason) {
System.out.println("WebSocket連接已關閉: " + session.getId());
}
@Override
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket發生錯誤: " + throwable.getMessage());
}
}
javax.websocket.server.ServerContainer
接口來實現這一點。通常,你可以在Servlet容器(如Tomcat)中注冊一個WebSocket端點,或者使用嵌入式服務器(如Jetty)來運行WebSocket服務器。以下是使用Servlet 3.1容器(如Tomcat)注冊WebSocket端點的示例:
import javax.websocket.ContainerProvider;
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;
@ServerEndpoint("/my-websocket")
public class MyWebSocketEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket連接已打開: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到客戶端消息: " + message);
// 處理消息并發送響應
try {
session.getBasicRemote().sendText("服務器已收到消息: " + message, result -> {
if (result.getException() != null) {
System.out.println("發送響應失敗: " + result.getException());
}
});
} catch (IOException e) {
System.out.println("發送響應失敗: " + e.getMessage());
}
}
@OnClose
public void onClose(Session session) {
System.out.println("WebSocket連接已關閉: " + session.getId());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket發生錯誤: " + throwable.getMessage());
}
}
/my-websocket
端點時,MyWebSocketEndpoint
類中的onMessage
方法將被調用,你可以在該方法中處理接收到的消息。