在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
方法将被调用,你可以在该方法中处理接收到的消息。