2016-11-06 117 views
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方法已被調用?

回答

0

因爲正常關閉ws連接是一個異步過程。您的服務器會發送一條關閉消息,但是直到服務器收到來自客戶端的密切回覆後,連接纔會關閉。根據你的觀察,客戶很可能已經發送了10個'你好!'消息甚至在它開始處理來自服務器的關閉消息之前。所以,就服務器而言,連接仍然是開放的,這就是它打印「服務器接收」消息的原因。