我開發的系統包括:Android Mobile上的套接字服務器和PC上的套接字客戶端。爲了檢查與客戶端的連接,我從服務器每1秒發送一個" "
字符。java.net.SocketException:發送失敗:EPIPE(Broken pipe)在發送字符時檢查套接字連接
但有時候,我得到了異常:
java.net.SocketException: sendto failed: EPIPE (Broken pipe)
at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:506)
at libcore.io.IoBridge.sendto(IoBridge.java:475)
at java.net.PlainSocketImpl.write(PlainSocketImpl.java:507)
at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:269)
at java.io.OutputStream.write(OutputStream.java:82)
at com.foxconn.cnsbgit.mobileterminal.MainActivity$ServerThread.run(MainActivity.jaa:527)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.ErrnoException: sendto failed: EPIPE (Broken pipe)
at libcore.io.Posix.sendtoBytes(Native Method)
at libcore.io.Posix.sendto(Posix.java:151)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:177)
at libcore.io.IoBridge.sendto(IoBridge.java:473)
... 6 more
發送Thread
檢查連接如下:
while (true) {
if (client != null) {
try {
client.getOutputStream().write(" ".getBytes()); // Get exception when sending character
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
txtConnectionStatus.setText(R.string.smoConnectOK);
}
});
} catch (Exception e) {
e.printStackTrace(); // Get exception at here
mHandler.post(new Runnable() {
@Override
public void run() {
if !txtConnectionStatus.getText().toString().contains("FAIL")) {
txtConnectionStatus.setText(R.string.connectionFailString);
}
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
更新時間: 然後,我有輸入和發送數據到客戶端。當心跳和數據同時發送時,連接是否丟失? :
public class SendDataThread implements Runnable {
@Override
public void run() {
try {
if (client != null) {
sendDataStream = client.getOutputStream();
sendDataStream.write(dataSend); //dataSend is a byte array
sendDataStream.flush();
mHandler.post(new Runnable() {
@Override
public void run() {
edtCommand.selectAll();
}
});
}
} catch (final Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
txtRec.setText(e.toString());
}
});
}
}
}
寫''「'經常可能是連接關閉的原因,兄弟? –
@MrNeo:「」不關閉連接,服務器。由於我不知道你的服務器是什麼,我不能確定是否太多「」會導致它關閉連接。 –
我已更新我的問題以獲取更多信息。當我同時發送心跳和數據時,我的連接是否丟失? –