socket连接失败抛异常,希望继续执行。

sunhao901001 2012-10-09 10:18:16
	@Override
public void run() {
while (!bExit ) {
try {
System.out.println("kaishile");
send();
System.out.println("开始了,开始了");
Thread.sleep(15000);
} catch( InterruptedException e) {
e.printStackTrace();
}
}
}
,15秒执行一次send();

private void send() {
try {
if( client == null || client.isClosed()) {
client = new Socket(InetAddress.getByName(mServerAddr),mServerPort);
client.setSoTimeout(60000);
client.setTcpNoDelay(true);
outP = client.getOutputStream();
inP = client.getInputStream();

_log.debug("new socket is created, device id is " + mDeviceID);
}
} catch (IOException e) {
System.out.println("报错了IOException");
e.printStackTrace();
_log.error("deviceID:" + mDeviceID + " IOException ");
try {
outP.close();
inP.close();
client.close();
client = null;
} catch (IOException e1) {
e1.printStackTrace();
}
}
,我故意将地址写错,当创建socket失败时,就抛出报 错了IOException
java.net.ConnectException: Connection timed out: connect,这样就停止了,但是我想不管你是不是报错,我就15秒执行一次程序,现在是报错后直接挂掉了,程序不走了,希望大侠来看看。。。
...全文
392 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
想喝咖啡的貓 2012-10-09
  • 打赏
  • 举报
回复
这样?


class TestClient1 implements Runnable{
Socket client = null;
InetSocketAddress serverAddress = null;
boolean bExit = false;

public TestClient1(){
this("127.0.0.1", 7777);
}

public TestClient1(String serverIp, int port){
this.serverAddress = new InetSocketAddress(serverIp,port);
}

@Override
public void run() {
for(int i=0;!bExit;i++){
if(connect2Server()){
//连接成功
}else{
System.out.println("连接失败,重试("+i+")...");
try {
Thread.sleep(1000*15);
} catch (InterruptedException e) {
}
}
}
}

boolean connect2Server(){
boolean done = false;

try{
client = new Socket();
client.connect(serverAddress, 1000*60);
client.setSoTimeout(60*1000);
done = client.isInputShutdown() & client.isOutputShutdown();
}catch(Exception ex){
System.err.println("报错了:"+ex.getMessage());
try{
if(null!=client) client.close();
}catch(Exception ex1){
}

done = false;
}

return done;
}
}
MiceRice 2012-10-09
  • 打赏
  • 举报
回复
暂时没看出什么大问题,不过:
你那么多的close(),居然不是写在finally里面?
你的client等变量,居然都是成员属性,而不是send()函数的局部变量?

sunhao901001 2012-10-09
  • 打赏
  • 举报
回复
呵呵,自己解决了,是由于没创建成功socket,就关闭,所以报错,关闭前判断socket不为空,并且socket没关闭,才进行关闭步骤。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧