android Socket通讯时readline阻塞

来源:互联网 发布:linux自杀命令 编辑:程序博客网 时间:2024/06/05 00:18

android编写了一个测试soket的例子,发现接收不到数据,跟踪调试发现是in.readLine()时造成阻塞。调试了很久才发现,下面代码并无问题。问题在于发送的数据没有包含换行符,程序认为line没有发送完毕,就一直阻塞了。只需在服务端发送数据时增加换行如\n. \r

public void run() {try {while (true) {if (socket.isConnected()) {if (!socket.isInputShutdown()) {if (in != null) {if ((content = in.readLine()) != null) {content += "\n";mHandler.sendMessage(mHandler.obtainMessage());out.println("got it.");}  }}}}} catch (Exception e) {e.printStackTrace();}}

0 0