写服务器对浏览器的响应:Java

时间:2011-10-20 19:45:13

标签: java http browser httpresponse

我有一个简单的HTML服务器程序,可以在端口8000上侦听请求。我希望能够从服务器程序请求HTML文件,并将请求的HTML发送回浏览器。目前,服务器接收请求并从请求中解析所请求的文件名,甚至将html文件的内容打印到控制台。但是,当我尝试将HTML文件内容打印到连接的套接字(返回浏览器)时,没有任何反应;浏览器只是继续加载。

我的服务器类相对简单,只为每个连接创建此runnable类的实例RequestHandler:

package server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class RequestHandler extends Thread {

    Object block;
    ServerSocket serverSocket;
    BufferedReader socketReader;
    PrintWriter socketWriter;

    public RequestHandler(Object block, ServerSocket serverSocket){
        this.block = block;
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try{
            System.out.println("Waiting for request...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Connection made.");

            synchronized(block){
                System.out.print("Notifying server thread...");
                block.notify();
                System.out.println("...done");
                System.out.println();
            }

            socketReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));            
            socketWriter = new PrintWriter(clientSocket.getOutputStream(), true);

            String input;
            while((input = socketReader.readLine()) != null){
//              System.out.println(input);

                if(input.startsWith("GET")){
                    getResource(input);
                }
            }
        }catch(IOException e){
            System.out.println("IOException!");
            e.printStackTrace();
        }
    }

    public void getResource(String getRequest){
        String[] parts = getRequest.split("\\s+");
        String filename = parts[1].substring(1);

        System.out.println(filename);
        File resource = new File(filename);             
        sendResponse(resource);
    }

    public void sendResponse(File resource){
        System.out.println(resource.getAbsolutePath());

        Scanner fileReader;
        try {
            fileReader = new Scanner(resource);

            while(fileReader.hasNext()){
                String line = fileReader.nextLine();
                System.out.println(line);
                socketWriter.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:3)

当您完成写入或从流中读取时,您应该始终做什么? (我知道你问题的答案,但我问这个问题,因为你把你的问题标记为“家庭作业”)