将HTTP请求重定向到不同的服务器

时间:2014-08-29 10:41:28

标签: java sockets http networking

我正在尝试实施故障转移系统。所以我创建了一个监控服务器,假设将请求路由到不同的应用服务器。

到目前为止,我设计了一个小型监控服务器,并尝试使用HTTP/1.1 302 Found\r\n状态代码路由请求。但我无法重定向到我的虚拟机,虽然我可以通过输入网址直接在我的浏览器上访问它。

路由代码 -

class Connection extends Thread{
    Socket clientSocket;
    BufferedReader din;
    OutputStreamWriter outWriter;

    public Connection(Socket clientSocket){
        try{
            this.clientSocket = clientSocket;
            din = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "ASCII"));
            outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
            this.start();
        }catch(IOException e){
            System.out.println("Connection: " + e.getMessage());
        }   
    }
    public void run(){
        try{
        String line = null;
        while((line = din.readLine())!=null){
            System.out.println("Read" + line);
            if(line.length()==0)    
                break;
        }
        //here write the content type etc details:
        System.out.println("Someone connected: " + clientSocket);

        }catch(EOFException e){
            System.out.println("EOF: " + e.getMessage());
        }
        catch(IOException e){
            System.out.println("IO at run: " + e.getMessage());
        }finally{
            try{
                routeRequest(outWriter);
                outWriter.close();
                clientSocket.close();
            }catch(IOException e){
                System.out.println("Unable to close the socket");
            }
        }
    }

    public void routeRequest(OutputStreamWriter outWriter){
        try {
            outWriter.write("HTTP/1.1 302 Found\r\n");
            outWriter.write("Date: Tue, 11 Jan 2011 13:09:20 GMT\r\n");         
            outWriter.write("Content-type: text/plain\r\n");
            outWriter.write("Server: vinit\r\n");           
            outWriter.write("Location: http://192.168.74.128:8080/Stateless/index.html");
            outWriter.write("Connection: Close");
            outWriter.write("\r\n\r\n");
//          String responseStr = "<html><head><title>Hello</title></head><body>Hello world from my server</body></html>\r\n";
//          outWriter.write(responseStr);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

但是在浏览器而不是路由上我得到没有数据接收页面。

如果我做错了,请告诉我。

PS:如果我使用状态200,我能够显示虚拟的hello world页面

提前致谢。

1 个答案:

答案 0 :(得分:3)

您的Location:标头缺少行尾指示符。

outWriter.write("Location: http://192.168.74.128:8080/Stateless/index.html\r\n");

如果缺少此选项,您的Connection:标题将成为重定向网址的一部分。客户端将保持与服务器的连接,除非您的服务器在发送此响应后明确关闭。

即使客户端超时并关闭连接,它也可能将URL视为无效。如果它确实重定向,那么将找不到页面,因为路径类似于:

  

/Stateless/index.htmlConnection: Close

相关问题