我正在使用套接字發送HTTP GET請求,以通過SCPI命令控制信號發生器。 我設法發送幾個請求並從服務器接收答案。發送HTTP Get Request時發生BufferedReader超時?
我的問題是,如果我等待大約15秒,然後再次發送請求,我沒有收到我的請求的任何答案。看來BufferedReader不再收到任何消息
我已經設置我的套接字的超時時間爲無限。看起來我的問題來自BufferedReader的「超時」,因爲他的ready
方法總是返回false。
再次接收消息的唯一解決方案是關閉並重新創建我的Socket,PrintWriter和BufferedReader。
我宣佈我的插座,爲PrintWriter和BufferedReader如下:
tcpIpSocket = new Socket(ipAddress, tcpPort);
printWriteOutputStream = new PrintWriter(tcpIpSocket.getOutputStream(),false);
bufferInputStream = new BufferedReader(new InputStreamReader(tcpIpSocket.getInputStream()));
我用一個單獨的函數來發送和接收我的HTTP GET請求作爲便接踵而來:
public static String sendRequestToSigGenerator(String scpiMessageToSend) throws Exception {
StringBuffer receivedHTTPMessages=new StringBuffer();
int receivedCharacterFromInputStreamInt;
printWriteOutputStream.println("GET /;:"+scpiMessageToSend+ " HTTP/1.0\r\n");
printWriteOutputStream.flush();
Thread.sleep(100); //Sleep needed for the buffer to be filled
while (bufferInputStream.ready()) {
receivedCharacterFromInputStreamInt = bufferInputStream.read();
receivedHTTPMessages.append((char)receivedCharacterFromInputStreamInt);
}
return(receivedHTTPMessages.toString());
}
不發送消息後15秒,併發送新的請求,while (bufferInputStream.ready()
保持始終爲假
編輯: 而不是實現我自己的HTTP,我使用的庫:java.net.URL;
這很容易處理我的查詢,避免我的問題:
public static String sendHTTPRequest(String scpiCommand) throws Exception {
try{
StringBuilder returnString= new StringBuilder();
URL url = new URL("http://"+ipAddress+"/;:"+scpiCommand);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
returnString.append(strTemp);
}
return(returnString.toString());
} catch (UnknownHostException e) {
return ERROR;
} catch (IOException e) {
return ERROR;
}
}
你爲什麼要自己實現HTTP?肯定會有問題。例如使用「.ready()」來檢查是否有更多的數據是錯誤的(並且會導致你解釋的那種問題)。另外:沒有保證TCP/IP連接仍然是開放的。實際上,由於您指明HTTP/1.0,所以發送響應後(如果我正確記住我的HTTP RFC正確;關鍵字:keep-alive),合規服務器將關閉連接。 –
你是否建議我應該使用類似HTTP庫的東西?我不知道(我遵循我想控制的設備的手動指令) – user2310493
我現在使用java.net.URL;它處理我的請求並避免我的問題。感謝您的幫助! – user2310493