簡體   English   中英

具有PrintWriter的簡單Java Server-向瀏覽器發送響應時出現問題

[英]Simple Java Server with PrintWriter - problem sending a response to browser

我剛剛開始研究HTTP等,並編寫了一個簡單的Java客戶端,該客戶端使用URLConnection將URL發送到服務器並拉下index.html頁面(以純文本格式)。

現在,我正在一個簡單的服務器上工作,但遇到了第一個障礙(可能是第2個或第3個),所以我無法使其正確響應客戶端。

這是循環讀取,它可以很好地讀取HTTP請求,甚至可以從FF和IE等讀取:

while((message = in.readLine()) != null)
    {
        System.out.println(message);
        out.write("something");
    }

問題是我不知道如何使它響應任何有用的事情。 如果我按照上面的代碼做它做的事情,它將向我的客戶端發送6次“內容”(因為HTTP請求有6行),但對FF / IE則什么也沒有發送。

另外,當我添加System.out.println("test");似乎也沒有中斷循環System.out.println("test"); 循環后要打印的行,但服務器似乎從未達到該點,對嗎? readLine()是否應該在第一個HTTP請求的末尾返回null?

我一直在閱讀sun和oracle網站上的內容,但是對於它應該如何工作仍然很困惑。

謝謝你的時間,

Infinitifizz

編輯:糟糕,忘記復制代碼了。

Server.java:

package exercise2;

import java.net.*;

public class Server 
{
    public static void main(String[] args) throws Exception
    {
        boolean listening = true;
        ServerSocket server = new ServerSocket(8081);

    while(listening)
    {
        Socket client = server.accept();

        new ServerThread(client).start();
    }
        server.close();
    }
}

ServerThread.java:

package exercise2;

import java.io.*;
import java.net.*;

    public class ServerThread extends Thread 
{
    private Socket socket = null;
    public ServerThread(Socket s)
    {
        this.socket = s;
    }

    public void run()
    {
        try
        {

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    socket.getInputStream()));

        String message, reply = "";

        while((message = in.readLine()) != null)
        {
            System.out.println(message);
            out.write("something");
        }
            System.out.println("test");
        in.close();
        out.close();
        socket.close();
        }
        catch(IOException e)
        {
            System.err.println("error");
        }
    }
}

在沒有看到您的客戶端代碼的情況下,這是我對發生的事情的最佳猜測:

您的服務器可能在該readLine()中阻塞,因為客戶端已完成寫入請求,但尚未關閉連接(應這樣做:客戶端應等待以獲取通過同一連接的響應)。 通常,HTTP服務器在讀取請求時會解析一個請求:基於 ,您可以查找“ \\ r \\ n \\ r \\ n”來划分標頭的末尾,然后從讀取循環中跳出至解析請求並響應。

首先,將while循環中的條件更改為
while(in.hasNextLine()) {
message = in.nextLine();
//etc....

其次,您無需在運行服務器時退出while循環。 您應該在while循環內對請求進行所有解析,並使用if語句來區分請求。 您唯一一次退出while循環的時間是連接應該關閉的時間,否則, nextLine()方法將阻塞,直到接收到某些內容為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM