in my java websocket, I would like to close the connection immediately after is has been established.
Server
@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;
}
Client
@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");
}
Although the connection has been closed in the onOpen method at the server class, it still receives the messages from the client.
server receives: Hello!
server receives: Hello!
server receives: Hello!
server receives: Hello!
...
Why is the connection still open and receives messages, although the close method has been called?