亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

websocket api開發客戶端如何保持鏈接不斷開,在沒有數據傳輸的時候

websocket api開發客戶端如何保持鏈接不斷開,在沒有數據傳輸的時候

哆啦的時光機 2019-02-18 22:39:32
最近用java websocket開發的客戶端程序,在和服務端鏈接通后,在數據傳輸完畢后,客戶端自動關閉了鏈接,如何能保持鏈接不斷開 這個是客戶端的啟動類,在循環完畢后,會自動斷開和服務器的鏈接,開始懷疑是session超時問題,然后設置了下maxsession,卻依然在沒有數據傳輸后立刻斷開了鏈接 public class ClientStart { public static void main(String[] args){ try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); MyClient client = new MyClient(); container.connectToServer(client, new URI("ws://localhost:8088/websocket")); // container.setDefaultMaxSessionIdleTimeout(5000L); int turn = 0; while(turn++ < 10){ client.send("client send: " + turn); Thread.sleep(1000); } }catch (Exception e){ e.printStackTrace(); } } } MyClient也放上去吧: @ClientEndpoint public class MyClient { private static Logger logger = LoggerFactory.getLogger(MyClient.class); private Session session; @OnOpen public void open(Session session){ logger.info("Client WebSocket is opening..."); this.session = session; } @OnMessage public void onMessage(String message){ logger.info("Server send message: " + message); } @OnClose public void onClose(){ logger.info("Websocket closed"); } /** * 發送客戶端消息到服務端 * @param message 消息內容 */ public void send(String message){ this.session.getAsyncRemote().sendText(message); } }
查看完整描述

3 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

new CountDownLatch(1).await();

查看完整回答
反對 回復 2019-03-01
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

按照你的邏輯循環發送消息結束后,進程就退出了吧,連接斷開是正常情況。

public class ClientStart {
    public static void main(String[] args){
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            MyClient client = new MyClient();
            container.connectToServer(client, new URI("ws://localhost:8088/websocket"));
//            container.setDefaultMaxSessionIdleTimeout(5000L);
            int turn = 0;
            while(turn++ < 10){
                client.send("client send: " + turn);
                Thread.sleep(1000);
            }
            
            //
            // wait/sleep
            //
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
查看完整回答
反對 回復 2019-03-01
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

要保證你的主線程一直不退出,例如spring mvc 的web框架,或者是一個阻塞的隊列,沒有消息就一直阻塞,保證主線程不會退出。Thread.sleep(1000);你可以嘗試把這個調成1h,模擬一個永不退出的程序

查看完整回答
反對 回復 2019-03-01
  • 3 回答
  • 0 關注
  • 1235 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號