我使用此代码在两个设备之间传输数据。
public void run() {
try {
Socket s = new Socket(myIpAddress, SERVERPORT);
// outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("DLS");
BufferedReader input = new BufferedReader(new InputStreamReader(
s.getInputStream()));
// read line(s)
String st = input.readLine();
// . . .
// Close connection
s.close();
} catch (UnknownHostException e) {
run();
e.printStackTrace();
} catch (IOException e) {
run();
e.printStackTrace();
}
}
我的问题是我必须先启动服务器,然后才能启动客户端以成功连接。
在里面
public void run()
我把run()
和UnknownHostException
放到IOException
. 它在其他代码中运行良好,但在这里我得到了StackOverFlowError
. 我怎样才能让它以有限的数量重新尝试,并且每 X 秒才尝试一次?
我尝试这种方式是因为run()
并且Thread.sleep(5000);
为未处理的异常而哭泣。当我启动服务时,应用程序被冻结。
public void run() throws UnknownHostException, IOException {
Socket s = new Socket(myIpAddress, SERVERPORT);
// outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("DLS");
s.close();
}
@Override
public void onCreate() {
for (int i = 0; i < 10; i++) {
try {
run();
break; // no exception: break out of the loop.
}
catch (IOException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}