我有点沉迷于如何避免我的插座挂在阅读.这是我的代码:
Socket socket = new Socket("someMachine",16003); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); try { outputStream.write(messageBuffer.toByteArray()); outputStream.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer response = new StringBuffer(); int result; while ((result = in.read()) != -1) { response.append(Character.tochars(result)); System.out.println(result); } System.out.println("Done!"); //never gets printed } catch (...) {}
上述代码成功读取流中的所有数据,但会挂起.在网上阅读我期望从服务器(我无法控制)收到一个-1表示我已经到达流的结束,但我得到这个:
(Lots of data above this point) 57 10 37 37 69 79 70 10
然后挂断所以我的问题是:
1)我编码错误或服务器的响应有问题吗?
2)如果服务器的响应出现问题(即没有返回-1),我该如何解决这个问题(即停止读取时挂起).
任何帮助赞赏!