好的,我需要编写一个能够检测到客户端和服务器之间连接的客户端...一旦服务器关闭并重新启动,我的客户端就需要能够将其重新连接到服务器..但是我真的不是确定如何做...如果有帮助的话吗?
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面是我的客户端代码,用于在服务器编译后用于连接服务器...
知道连接已关闭的唯一方法是尝试通过线路发送数据。连接不会自动测试打开/关闭状态。如果要检查是否已关闭连接并重新连接,则必须将心跳信号从一个发送到另一个。通常,它只是一个特殊的字节或微小的消息,告诉对方“我还在这里”
但是,然后,根据您的应用程序,您可能不需要。您的应用程序的两面都启动消息吗?还是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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18288 次 |
| 最近记录: |