WebSocket异常:The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method

 

项目中websocket,sendMessage出现异常。

 

代码:

this.session.getAsyncRemote().sendText(text);

 

 

原因:

一种是,onMessage方法有返回值,导致onMessage无法被sync block控制。

 

一种是,session没有被同步控制,导致多线程情况下,出现IllegalStateException

 

保证以上两点之后

 

使用session.getBasicRemote()应该是没有问题的。

 

 

 

方案:

 

方案1:同步控制 + 异步发送

public void sendMsg(String text) {

  log.info("即将推送消息给客户:" + text);

  if (!this.session.isOpen()) {

   log.error("消息推送失败,session 处于关闭状态:" + session.getId());

   return;

  }

 

  synchronized (session) {

   try {

    Thread.sleep(1000 * 5);

   } catch (InterruptedException e1) {

    e1.printStackTrace();

   }

   if (this.session.isOpen()) {

    try {

     this.session.getAsyncRemote().sendText(text);

    } catch (IOException e) {

     e.printStackTrace();

     log.error(e.getMessage());

    }

   } else {

    log.error("消息推送失败,session 处于关闭状态:" + session.getId());

   }

  }

 }

 

方案2:同步控制 + 同步发送

 

 public void sendMsg(String text) {

  log.info("即将推送消息给客户:" + text);

  if (!this.session.isOpen()) {

   log.error("消息推送失败,session 处于关闭状态:" + session.getId());

   return;

  }

 

  synchronized (session) {

   try {

    Thread.sleep(1000 * 5);

   } catch (InterruptedException e1) {

    e1.printStackTrace();

   }

   if (this.session.isOpen()) {

    // this.session.getAsyncRemote().sendText(text);

    try {

     this.session.getBasicRemote().sendText(text);

    } catch (IOException e) {

     e.printStackTrace();

     log.error(e.getMessage());

    }

   } else {

    log.error("消息推送失败,session 处于关闭状态:" + session.getId());

   }

  }

 }

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐