我有一個Java程序從TCP源讀取數據的工作都很好,除非我的程序(它充當數據源的客戶端)比那時更快源可以響應BufferedReader.ready()拋出一個異常,它會關閉我的TCP連接,因爲它應該如此。是否有任何首選的方法/方法可以讓BufferedReader等待新的輸入,因爲我的源有時可能會有輕微的延遲。緩衝套接字讀取器不等待遠程連接的數據
這是我講的一部分:你不應該使用ndataServerReader.ready()
public aDataServer(String host, int port, StreamConnection aConnection) throws UnknownHostException, IOException {
this.aConnection = aConnection;
ndataServerSocket = new Socket(Inet4Address.getByName(host),port);
ndataServerReader = new BufferedReader(new InputStreamReader(ndataServerSocket.getInputStream()));
}
public void run() {
try {
RemoteDevice dev = RemoteDevice.getRemoteDevice(aConnection);
OutputStream outputStream = aConnection.openOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(outputStream);
do {
try {
String ndata = ndataServerReader.readLine();
osw.write(ndata+"\n");
osw.flush();
LOG.log(Level.INFO,"Sent");
} catch(IOException io) {
LOG.log(Level.SEVERE, "Client device({0}) disconnected: \n{1}", new Object[]{dev.getFriendlyName(true), io.getMessage()});
break;
}
}while(ndataServerReader.ready());
} catch (IOException ioe) {
LOG.severe(ioe.getMessage());
} finally {
try {
if (ndataServerSocket != null) {
ndataServerSocket.close();
}
if (ndataServerReader
!= null) {
ndataServerReader.close();
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, ex.getMessage());
}
}
什麼是拋出異常?你能否包含你如何構建和讀取BufferedReader的代碼片段? – dimo414 2013-03-10 19:43:19
用一些代碼更新了我的問題 – user1945235 2013-03-10 19:53:04
您是否也可以發佈異常輸出? – dimo414 2013-03-10 19:58:38