客户端从Web服务器请求

时间:2013-09-18 18:05:44

标签: java

我编写了一个简单的java客户端来发送请求并从我的java web服务器接收数据。服务器能够处理持久连接,当我使用浏览器发送请求时一切正常,但是当我使用我的客户端发送请求时,它只适用于非持久连接。当我使用我的java客户端发送请求时,它将接收从服务器请求的数据,然后冻结。我的java客户端代码:

     public static void main(String[] args) throws UnknownHostException, IOException {
        // TODO code application logic here
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("127.0.0.1", 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        System.out.println("Enter the file name that you would like to request from Server:");
        sentence = inFromUser.readLine();

        System.out.println("would you like to have a persistent connection (yes/no):");
        String sentence1 = inFromUser.readLine();
        if(sentence1.equals("yes")){sentence1="Connection: keep-alive";}

        else{sentence1="Connection: close";}
        outToServer.writeBytes("GET /"+sentence + "\r\n");
        outToServer.writeBytes(sentence1+"\r\n");
        outToServer.writeBytes("\r\n");

        while ((modifiedSentence=inFromServer.readLine()) != null) 
        {
              System.out.println("FROM SERVER: " + modifiedSentence);
        }

        System.out.println("done");

        clientSocket.close();
    }

1 个答案:

答案 0 :(得分:0)

我的猜测是,在服务器关闭连接(关闭套接字和其他流)之后,您尝试modifiedSentence=inFromServer.readLine()并获得java.net.SocketException

尝试使用try / catch包围它并打印错误消息/ stacktrace