服務器是否可能知道客戶端已經完成數據發送並且現在已準備好進行響應 - 無論(並且沒有知識)應用協議?服務器是否可能知道TCP流已經「完成」而不管協議?
編輯: 想想創建一個代理服務器。你不能影響協議,你不知道每個協議的應用細節(所以你不知道流何時「結束」)。關於「客戶可能關閉輸入流」 - 這是真的,但顯然客戶並沒有真正關閉流(與重用有關)。這是通過Web瀏覽器進行實證測試的。
雖然我可能會在錯誤的樹上吠叫 - 對於那個代理服務器場景,不會將流複製到「另一端」的輸出流就夠了嗎?但是,另一端如何「知道」該流已結束?
看到這個程序:
public class Test {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8081, 100, InetAddress.getByName("localhost"));
final Socket socket1 = new Socket("www.google.com", 80);
final Socket socket = serverSocket.accept();
new Thread(new Runnable() {
public void run() {
try {
final InputStream inputStream = socket1.getInputStream();
final OutputStream outputStream = socket.getOutputStream();
readwrite(inputStream, outputStream, false);
} catch (IOException e) {
e.printStackTrace();
}
}
});
final InputStream inputStream = socket.getInputStream();
final OutputStream outputStream1 = socket1.getOutputStream();
readwrite(inputStream, outputStream1, true);
}
private static void readwrite(InputStream inputStream, OutputStream outputStream1, boolean x) throws IOException {
final byte[] bytes = new byte[4];
int read = -1;
while ((read = inputStream.read(bytes)) != -1) {
System.out.println((x?"s ":"r ") + new String(bytes));
outputStream1.write(bytes, 0, read);
}
}
}
而不是做什麼,你會覺得它會做(在瀏覽www.google.com代理)的它只是掛起。應該從google讀取並寫入本地套接字的線程不會檢測到該輸入流中的任何內容。
編輯2: DOH! 把我放在愚蠢的角落。忘了「開始」線程。 回到我原來的問題 - 我怎麼知道流已經結束?
編輯3: 那麼,我的問題是完全不同的(與POST,Transfer-Encoding和HttpClient惱人的內部緩存 - 不能關閉)。 爲了公平起見,我會接受最好回答原始問題的答案。