1

私は次の問題を抱えています...

            try 
            {
                clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));

                while(true)
                { 
                    String clientRequest = "";
                    String tempStr = clientInput.readLine();

                    while(tempStr != null && !tempStr.equals("null"))
                    {
                        System.out.println(tempStr);
                        clientRequest += tempStr + " ";
                        tempStr = clientInput.readLine();
                    }

                    //Parse Request
                    ArrayList<String> tokenArray = parseRequest(clientRequest);

                    Calendar c = Calendar.getInstance();

                    switch(tokenArray.get(0))
                    {
                        case "GET": 
                        {
                            clientOutput.write("HTTP/1.1 200 OK\r\n");
                            clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
                            clientOutput.write("Server: Java HTTP Server v1.0\r\n");
                            clientOutput.flush();
                            break;
                            //Write File
                        }
                        default: 
                        {
                            clientOutput.write("500\r\n");
                            clientOutput.flush();
                        }
                    }
                } 
            }

すべてが完全に正常に機能しclientOutput.write("HTTP.......、クライアントは待機し続けます...私はすべての連続した書き込みの後にフラッシュしようとしましたが、まだ何もありません.....しかし、これは奇妙な部分です-もし私がコードがwhileループに入る前に書き込みとフラッシュを行うと、書き込みはcase "GET":完全に機能します......つまり

コードは、

                            clientOutput.flush();
                            break;
                            //Write File

              try 
             {
                clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));

                clientOutput.write("HTTP/1.1 200 OK\r\n");
                clientOutput.flush();

                while(true)
                { 
                    String clientRequest = "";
                    String tempStr = clientInput.readLine();

                    while(tempStr != null && !tempStr.equals("null"))
                    {
                        System.out.println(tempStr);
                        clientRequest += tempStr + " ";
                        tempStr = clientInput.readLine();
                    }

                    //Parse Request
                    ArrayList<String> tokenArray = parseRequest(clientRequest);

                    Calendar c = Calendar.getInstance();

                    switch(tokenArray.get(0))
                    {
                        case "GET": 
                        {
                            clientOutput.write("HTTP/1.1 200 OK\r\n");
                            clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
                            clientOutput.write("Server: Java HTTP Server v1.0\r\n");
                            clientOutput.flush();
                            break;
                            //Write File
                        }

これがクライアントのコードです

        Socket s = new Socket("localhost", 1337);

        BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));

        toServer.write("GET index.html HTTP/1.1\r\n");
        toServer.write("HOST: 127.0.0.1\r\n");
        toServer.write("Connection: close\r\n");
        toServer.write("\r\n");
        toServer.write("null\r\n");
        toServer.flush();   

        while(true)
        {
            String ss = fromServer.readLine();
            if(ss != null && !ss.equals("null"))
                System.out.println(ss);
        }

サーバークラス:Strydom_A_201103578_P03

public class Strydom_A_201103578_P03
{
    Thread[] threadArray = new Thread[5];
    int ClientCount = 0;

    public Strydom_A_201103578_P03() throws ClientSizeExceededException 
    {
        ServerSocket httpServer = null;
    try 
    {
        httpServer = new ServerSocket(1337);
    } 
    catch (IOException ex) 
    {
        Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
    }

    while(true)
    {
        try
        {
            //Wait for connection

            Socket clientSocket = httpServer.accept();

            if(ClientCount < 5)
            {
                threadArray[ClientCount] = new Thread(new clientHandler(clientSocket));
                threadArray[ClientCount].start();
                ClientCount++;
            }
            else
            {
                throw new ClientSizeExceededException();
            }

        }
        catch(IOException ex)
        {

        }
        finally
        {

        }
    }
}

class clientHandler implements Runnable
{
    Socket clientSocket;
    public clientHandler(Socket clientSocket) 
    {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() 
    {
        BufferedReader clientInput = null;
        BufferedWriter clientOutput = null;

            try 
            {
                clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));

                clientOutput.write(" ");
                clientOutput.flush();

                while(true)
                { 
                    String clientRequest = "";
                    String tempStr = clientInput.readLine();

                    while(tempStr != null && !tempStr.equals("null"))
                    {
                        System.out.println(tempStr);
                        clientRequest += tempStr + " ";
                        tempStr = clientInput.readLine();
                    }

                    //Parse Request
                    ArrayList<String> tokenArray = parseRequest(clientRequest);

                    Calendar c = Calendar.getInstance();

                    switch(tokenArray.get(0))
                    {
                        case "GET": 
                        {
                            clientOutput.write("HTTP/1.1 200 OK\r\n");
                            clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
                            clientOutput.write("Server: Java HTTP Server v1.0\r\n");
                            clientOutput.flush();
                            break;
                            //Write File
                        }
                        default: 
                        {
                            clientOutput.write("500\r\n");
                            clientOutput.flush();
                        }
                    }
                } 
            }
            catch (IOException ex) 
            {
                Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
            } 
            finally 
            {
                try 
                {
                    clientInput.close();
                    clientOutput.close();
                } 
                catch (IOException ex) 
                {
                    Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }

    private ArrayList<String> parseRequest(String tempStr) 
    {
        StringTokenizer httpTokens = new StringTokenizer(tempStr, " ");
        ArrayList<String> tokens = new ArrayList<>();

        while(httpTokens.hasMoreTokens())
            tokens.add(httpTokens.nextToken());

        return tokens;
    }
}


public static void main(String[] args) throws ClientSizeExceededException 
{
    new Strydom_A_201103578_P03();
}

}

public class TestClient 
{

public TestClient() 
{
    try 
    {
        Socket s = new Socket("localhost", 1337);

        BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));

        toServer.write("GET index.html HTTP/1.1\r\n");
        toServer.write("HOST: 127.0.0.1\r\n");
        toServer.write("Connection: close\r\n");
        toServer.write("\r\n");
        toServer.write("null\r\n");
        toServer.flush();   

        while(true)
        {
            String ss = fromServer.readLine();
            if(ss != null && !ss.equals("null"))
                System.out.println(ss);
        }

    } 
    catch (UnknownHostException ex) 
    {
        Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
    } 
    catch (IOException ex) 
    {
        Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}



public static void main(String[] args) 
{
    new TestClient();
}

}

クライアントクラス:TestClient

プロジェクト(または2)を作成し、ファイルを実行します

4

4 に答える 4

2

ここでの問題は、PrintWriter. 例外を飲み込みます。に変更しOutputStreamWriterます。次に、飲み込まれている例外が表示されます。PrintWriters一般に、ネットワーク経由は避ける必要がPrintOutputStreamsあります。彼らはあなたが知る必要がある例外を飲み込みます。

于 2012-08-05T22:50:15.493 に答える
0

クライアントのリクエストの最後を探すために、内側の while ループを変更する必要があります。

while(tempStr != null && !tempStr.equals("null"))

に:

while(tempStr != null && !tempStr.equals("null") && !tempStr.equals(""))

リクエストを送信した後、クライアントは切断されません (null が発生します)。リクエストの終了を示す空白行が表示されます。

応答ヘッダーをすぐに返すことが機能する理由は? おそらく、クライアントは 200 を読み取るだけで、(最終的には) 切断されますか? したがって、クライアントのリクエストを読み取っているときは終了し、最終的には null になります。


編集:

あなたのコードを実行すると、私にとってはうまくいきます。クライアントとサーバーの両方が、要求と応答の両方を送受信しています。ただし、サーバーが切断されることはなく (クライアントにはConnection: closeヘッダーが含まれます)、クライアントは で引き続きブロックされreadLine()ます。当然のことながら、サーバー側で接続をセットアップした直後にwrite()andを含めても、クライアント側で 2 回表示される以外は何も変わりません。たぶん、あなたがする必要があるのは、あなたの?の最後にあるブロック内を閉じることだけです。flush()HTTP/1.1 200 OKclientSocketfinally{}try/catch{}

于 2012-08-05T15:34:49.693 に答える
-1

これを行うだけでうまくいきます........

true の 2 番目のパラメーターとして追加します。PrintWriter

clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream(), true));

于 2012-08-05T15:53:10.237 に答える