BufferedWriter不会刷新

时间:2012-08-05 15:25:40

标签: java http sockets client-server printwriter

我有以下问题......

            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.......行, 客户端只是等待和等待...我已经尝试在每次成功写入后尝试刷新但是没有.....但这是奇怪的部分 - 如果我在代码进入之前写入并刷新 - 循环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)并运行文件

5 个答案:

答案 0 :(得分:1)

这里的问题是PrintWriter。它吞没了例外。将其更改为OutputStreamWriter。然后你会看到任何被吞下的异常。通常,您应该通过网络避免PrintWriters和PrintOutputStreams。

答案 1 :(得分:0)

您需要更改内部while循环以查找客户端请求的结束:

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

为:

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

客户端在发送请求后不会断开连接(导致null)。它会给你一个空行,表示请求的结束。

立即返回响应标头的原因是什么?也许客户端只读取200和(最终)断开连接?因此,当您阅读客户端的请求时,它会结束,最终会得到一个空值。


编辑:

所以运行你的代码,它对我来说很好。客户端和服务器都在发送和接收请求和响应。但是,服务器永远不会断开连接(客户端包含Connection: close标头),客户端继续阻止readLine()。不出所料,当我在服务器端设置连接后立即包含write()flush()时没有任何变化,除了我在客户端看到HTTP/1.1 200 OK两次。您可能需要做的只是关闭clientSocket末尾的finally{}区块中的try/catch{}

答案 2 :(得分:0)

这样做就可以了..........

true

中添加PrintWriter 作为第二个参数

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

答案 3 :(得分:0)

因此,为了延续我现在已经结束的痛苦 - 这就是我最终所做的......

我将服务器和客户端读者从BufferedReader/Writer更改为DataInputstream/OutputStream ....现在它完美无缺 - !谢谢大家

艾登

答案 4 :(得分:0)

对我来说,它有效。

*** BREAK LINE:此行中断对于浏览器解读标题结束和内容开始非常重要。没有它,冲洗不工作,响应不发送。

out.write("GET HTTP/1.0\r\n")
out.write("Accept: text/plain, text/html, text/*\r\n")
out.write("\r\n") // THIS BREAK LINE ***
out.write("It Works")
out.flush()
out.close()