在我的java websocket中,我想在连接建立后立即关闭连接。
服务器@ServerEndpoint(value = "/server")
public class Server {
private static final long serialVersionUID = 1L;
private Session session;
@OnOpen
public void onOpen(Session session) throws IOException {
System.out.println("Server Websocket open");
this.session = session;
try {
session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "No Token"));
} catch (IOException e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message) {
System.out.println("server receives: "+message);
}
@OnClose
public void onClose(Session session) {
System.out.println("Server session closed");
session = null;
}
客户@ClientEndpoint
public class Client {
public static void main(String[] args) {
WebSocketContainer container = null;
container = ContainerProvider.getWebSocketContainer();
try {
Session session = container.connectToServer(Client.class, URI.create("ws://localhost:8080/WebsocketServer/server"));
} catch (DeploymentException | IOException e) {
e.printStackTrace();
}
}
@OnOpen
public void onOpen(Session p) {
try {
for (int i = 0; i < 10; i++) {
p.getBasicRemote().sendText("Hello! ");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@OnClose
public void OnClose() {
System.out.println("Client connection closed");
}
虽然连接已经在服务器类的onOpen方法中关闭,但它仍然接收来自客户端的消息。
server receives: Hello!
server receives: Hello!
server receives: Hello!
server receives: Hello!
...
为什么连接仍然打开并接收消息,尽管已经调用了close方法?
因为优雅地关闭ws连接是一个异步过程。您的服务器发送一个关闭消息,但是直到服务器从客户端收到关闭回复后,连接才会关闭。根据你的观察,客户很可能已经发送了10个"Hello!"在它开始处理来自服务器的关闭消息之前。因此,就服务器而言,连接仍然是打开的,这就是为什么它打印"服务器接收"消息的原因。