如何检测Jetty WebSocket丢失的连接

时间:2016-12-22 09:15:10

标签: websocket jetty

我使用WebSocket确保两个独立jar之间的通信。第一个是启动嵌入式Jetty并部署WebSocket,第二个是Jetty WebSocket客户端,它发送命令并等待处理服务器部分。

服务器:

import java.io.IOException;

import javax.websocket.*;

@ClientEndpoint
@ServerEndpoint(value = "/websocket-api", encoders = {     NotificationEncoder.class }, decoders = { NotificationDecoder.class })
public class APIWebsocket {

  private static final Logger log = LoggerFactory.getLogger(APIWebsocket.class);

  @OnOpen
  public void open(Session session) {
    log.info("Session opened...");

  }

  @OnClose
  public void close(Session session) throws IOException {
    session.close();
    log.info("Session closed !");
  }

  @OnError
  public void onError(Throwable error) {
    log.error("Error during websocket session : {}", error.getMessage());
    log.debug("{}", error);
  }

  @OnMessage
  public void handleMessage(String message, Session session) {

       log.info("Message received : {}", message);

       List<Data> datas = JSONHelper.toCollection(message);
       for (Data data : datas){
          // do process with average time 30sec...
          // send notification of processing
          Notification unitNotification= new Notification("PROCESSED");
          session.getBasicRemote().sendObject(unitNotification);
       }

      // Build and send end notification message
      Notification endProcessNotification = new Notification("END OF PROCESS");
      session.getBasicRemote().sendObject(endProcessNotification);

    } catch (EncodeException | IOException e) {
      log.error(e.getMessage(), e);
      // Manage error

    } finally {
      try {
        session.close();
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        // Manage error
      }

    }

  }

}

客户端:

import java.io.IOException;
import java.net.URI;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.client.WebSocketClient;


public class WebsocketClient extends WebSocketAdapter {

  private static final Logger log = LoggerFactory.getLogger(WebsocketClient.class);
  private Session session = null;

  public APIWebsocketClient(String uri) {
    try {
      WebSocketClient client = new WebSocketClient();
      client.setMaxIdleTimeout(35 * 1000L);

      client.start();
      client.connect(this, new URI(uri)).get();

    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

  }

  public void startProcess(String datas) {
    try {
      session.getRemote().sendString(datas);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
  }

  @Override
  public void onWebSocketText(String message) {
    log.info("Message received : {}", message);
  }

  @Override
  public void onWebSocketClose(int statusCode, String reason) {
    log.info("Websocket closed ! [statusCode={}, reason={}]", statusCode, reason);
    this.session.close();
  }

  @Override
  public void onWebSocketConnect(Session session) {
    this.session = session;
    log.info("Websocket Client details : {}-{}", session.getLocalAddress().getHostName(), session
        .getLocalAddress().getAddress().getHostAddress());
  }

  @Override
  public void onWebSocketError(Throwable cause) {
    log.error("Error during websocket execution : {}", cause.getMessage(), cause);

    if (this.session != null) {
      this.session.close();
    }
  }

}

我的目标是检测客户端和服务器之间的网络通信是否丢失。如果我通过断开网络线来模拟网络丢失,WebSocket应检测服务器端和客户端的通信错误。

您是否知道如何继续检测客户端和服务器之间的网络丢失?

1 个答案:

答案 0 :(得分:-1)

这是Java。

仅在读/写事件中检测到连接丢失。 不是物理网络丢失。

如果您使用的是Android,则可以使用Android专用API来检测网络状态。