最近用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貢獻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();
}
}
}

蕪湖不蕪
TA貢獻1796條經驗 獲得超7個贊
要保證你的主線程一直不退出,例如spring mvc 的web框架,或者是一個阻塞的隊列,沒有消息就一直阻塞,保證主線程不會退出。Thread.sleep(1000);你可以嘗試把這個調成1h,模擬一個永不退出的程序
添加回答
舉報
0/150
提交
取消