gpt4 book ai didi

java - 客户端重新连接java套接字

转载 作者:行者123 更新时间:2023-12-01 17:32:19 25 4
gpt4 key购买 nike

好吧,我需要编写一个能够检测客户端和服务器之间的连接的客户端...一旦服务器关闭并恢复我的客户端需要能够将其连接回服务器..但是我我真的不知道该怎么做...如果可能的话有什么帮助吗?

 public TEST(String serverIP, int serverPort){
Log("Connection to the Server....");
try{
socket = new Socket(serverIP, serverPort);
Log("Connected to the server : "+socket);
start();
} catch(UnknownHostException uhe){
System.out.println("Unknown Host: "+ uhe.getMessage());
} catch (IOException ioe){
System.out.println("IO Exception: "+ioe.getMessage());
}

String readline = "";

streamOutput.println("TRY test");

while(true){
try{
readline = streamInput.readLine();
System.out.println(readline);
} catch (IOException ioe){
System.out.println("Error in sending: "+ioe.getMessage());
return;
}
}
}

上面是我的客户端代码,编译后用于连接到服务器...

最佳答案

了解连接已关闭的唯一方法是尝试通过线路发送数据。连接不会自动测试打开/关闭状态。如果您想检查关闭的连接并重新连接,则必须从一个连接到另一个连接发送心跳信号。通常,它只是一个特殊的字节或微小的消息,告诉对方“我还在这里”

但是,根据您的应用程序,您可能不需要它。您的应用程序的双方都会启动消息吗?或者它是一个 RMI 风格的应用程序?服务器在哪里只监听请求?

也许是这样的?

    class Client {
private Socket socket;
private boolean tryToReconnect = true;
private final Thread heartbeatThread;
private long heartbeatDelayMillis = 5000;

public Client(final String server, final int port) {
connect(server, port);
heartbeatThread = new Thread() {
public void run() {
while (tryToReconnect) {
//send a test signal
try {
socket.getOutputStream().write(666);
sleep(heartbeatDelayMillis);
} catch (InterruptedException e) {
// You may or may not want to stop the thread here
// tryToReconnect = false;
} catch (IOException e) {
logger.warn("Server is offline");
connect(server, port);
}
}
};
};
heartbeatThread.start();
}

private void connect(String server, int port){
try {
socket = new Socket(server, port);
} catch (UnknownHostException e) {
logger.error(e, e);
} catch (IOException e) {
logger.error(e, e);
}
}

public void shutdown() {
tryToReconnect = false;
}
}

关于java - 客户端重新连接java套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com