【发布时间】:2015-10-27 06:13:55
【问题描述】:
我开发的系统包括:Android Mobile上的socket server和PC上的socket client。为了检查与客户端的连接,我每 1 秒从服务器发送一个 " " 字符。
但有时,我得到了例外:
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());
}
});
}
}
}
【问题讨论】:
标签: java android multithreading sockets