您的位置:首页 > 编程语言 > Java开发

java Socket的怪异之处

2016-05-05 00:00 501 查看
摘要: 怪异之一:
connect(SocketAddress endpoint):这个方法,尝试连接server端,如果连接不上,就抛出IOException异常。如果连接成功了,就继续执行下一步的代码。

怪异之二:
boolean isConnected() :这个方法的结果仅仅代表这个socket曾经成功连接到了server,但并不表示现在这个时刻它和server仍保持连接状态。
有心的人会发现,即使你已经切断了server和socket之间的连接(比如server down掉了或网络中断了),但是这个函数执行的结果仍旧是true。所以,我认为这个方法并不像我们想象中的那么“管用”。
...

public class ClientAgainConnect implements Runnable {

private boolean isReConn = true;
private static final int DELAY_TIME = 5000;
private Socket mClientSocket = null;
private Handler mHandler;
private int mType = -1;

public void run() {
while (isReConn) {
holdTime(DELAY_TIME);
}
}

public void closeReConn(){
isReConn = false;
}

public ClientAgainConnect(Socket clientSocket,Handler handler,int type) {
this.mType = type;
this.mClientSocket = clientSocket;
this.mHandler = handler;
initiate();
}

private void holdTime(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
sendReConnData();
}

private void sendReConnData() {
try {
if (mClientSocket != null && mClientSocket.isConnected()) {
mClientSocket.sendUrgentData(0xFF);
}
} catch (IOException e) {
mHandler.sendEmptyMessage(mType);
initiate();
}
}

// 启动重连线程
private void initiate() {
new Thread(ClientAgainConnect.this).start();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Socket