在我的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方法?
答案 0 :(得分:1)
因为正常关闭ws连接是一个异步过程。您的服务器发送关闭消息,但在服务器收到客户端的关闭回复之前,连接不会关闭。鉴于您的观察结果,客户很可能已经发送了10&#39; Hello!&#39;甚至在它开始处理来自服务器的关闭消息之前的消息。因此,就服务器而言,连接仍然是开放的,这就是为什么它打印服务器接收&#34;消息。