0
在我的java websocket中,我想立即關閉連接。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方法已被調用?