当前位置: 动力学知识库 > 问答 > 编程问答 >

Android,Java,socket, determine remote host disconnect

问题描述:

I'm trying to code a TCP client in android java. Most works fine. But i have one issue. If the socket is connected and the remeote host shuts down or the network goes down or something else, the socket.getinputstream keeps blocking.

I don't know if the socket is still connected. I code in objective-c too and in objective-c i get an event that the socket forcefully shuts down and i can try to reconnect. So on objective c the socket tracks the state.

In java the socket and the inputstream is still connected or blocked even the socket is down. How can i check if the socket is still connected?

 @Override

protected Void doInBackground(String... params) {

try {

String host = params[0];

int port = Integer.parseInt(params[1]);

SocketAddress sockaddr = new InetSocketAddress(host, port);

Socket socket = new Socket();

socket.connect(sockaddr,5000);

socket.setSoTimeout(7000);

out = new PrintWriter(socket.getOutputStream(), true);

mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while (mRun) {

try {

-----> mServerMessage = mBufferIn.readLine();

}catch (Exception e){

Log.d("my","hier3" + e.getMessage());

}

if (mServerMessage.trim() != null) {

sender.messageReceived(s2);

}else{

}

}

}

} catch (UnknownHostException e

) {

网友答案:

The question of how to detect if the remote peer/socket has closed the connection has been answered here as well as here. Basically, the answers suggest that you attempt to read from the socket, and then observe what happens (read() returns -1, or readLine() returns null or your read methods raise EOFException.

分享给朋友:
您可能感兴趣的文章:
随机阅读: