0

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?

asked Nov 6, 2016 at 19:05

1 Answer 1

1

Because gracefully closing the ws connection is an asynchronous process. Your server sends a close message, but the connection is not closed until the server has received the close reply from the client. Given your observations, it's very likely that the client has already sent the 10 'Hello!' messages before it even started to process the close message from the server. So, as far the server is concerned, the connection is still open and that's why it prints the "server receives" messages.

answered Sep 5, 2017 at 20:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.