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. 然后你会看到任何被吞没的异常。一般来说,你应该避免PrintWritersPrintOutputStreams通过网络。他们吞下您需要了解的异常情况。

于 2012-08-05T22:50:15.493 回答
0

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

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

到:

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

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

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


编辑:

所以运行你的代码,它对我来说很好。客户端和服务器都在发送和接收请求和响应。但是,服务器永远不会断开连接(客户端包含一个Connection: close标头)并且客户端会继续阻止readLine(). 不出所料,当我在服务器端建立连接后立即包含write()and时,除了我在客户端看到两次之外,没有任何变化。也许你需要做的就是在你的?flush()HTTP/1.1 200 OKclientSocketfinally{}try/catch{}

于 2012-08-05T15:34:49.693 回答
0

因此,为了让我现在结束的痛苦更加痛苦——这就是我最终所做的……

我将服务器和客户端的阅读器都从.... 更改BufferedReader/WriterDataInputstream/OutputStream现在完美运行 - !谢谢大家

艾登

于 2012-08-05T18:12:26.197 回答
-1

只需这样做,它就会起作用.......

添加true 为第二个参数PrintWriter

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

于 2012-08-05T15:53:10.237 回答