简体   繁体   English

将套接字输入流从另一个套接字重定向到输出流

[英]Redirect Socket Inputstream to Outputstream from another socket

im trying to listen on HTTP requests for an website in my application.我试图在我的应用程序中收听 HTTP 对网站的请求。 My application is used to extract some data from the inputstream of Socket1 and forward it to the output stream of another socket2 (the client socket2 which connects to the actual webserver).我的应用程序用于从 Socket1 的输入流中提取一些数据并将其转发到另一个 socket2(连接到实际 web 服务器的客户端 socket2)的 output stream 。 The webserver should anser (->Inputstream2) and i want to pass it back to outputstream1 of socket1.网络服务器应该分析(-> Inputstream2),我想将它传递回socket1的输出流1。 The real webserver is getting an request, but im not receiving an answer, in this constellation.在这个星座中,真正的网络服务器正在收到请求,但我没有收到答案。 I read, that i have to close the output stream of an socket bevor can start to read the inputstream, so I also tried socket.shutdownOutput() but it's still not working.我读到,我必须关闭一个套接字的 output stream 才能开始读取输入流,所以我也尝试了 socket.shutdownOutput() 但它仍然无法正常工作。

I would appriciate any help我会给予任何帮助

private static void runHttpListener(Boolean simulate){
    try {
        ServerSocket server = new ServerSocket(PORT_HTTP_REQUEST);
        System.out.println("HTTP listener active on Port "+PORT_HTTP_REQUEST);
        boolean keepAlive = true;
        while (keepAlive) {               
            //Empfangen und auslesen
            Socket socketReceivingProxy = server.accept();  
            System.out.println("HTTP-Listener: Accepted client connection");              
            InputStream proxyInputStream = socketReceivingProxy.getInputStream();
            OutputStream proxyOutputStream = socketReceivingProxy.getOutputStream();
            //TODO: extract information from stream
            
            //forward
            InputStream result = sendHttpRequestToDestination(proxyInputStream, simulate);
            result.transferTo(proxyOutputStream);
            

            result.close();
            proxyOutputStream.close();
            socketReceivingProxy.close();
        }
        server.close();  
        System.out.println("HTTP listener closed");    
    } catch (Exception e) {
        e.printStackTrace();
    }

My forwarding method is realy simple but it doesn't actually works:我的转发方法非常简单,但实际上并不起作用:

private static InputStream sendHttpRequestToDestination(InputStream incomingRequest, Boolean simulate){
    try{
        
        Socket socketForwardingWebapp = new Socket(simulate?URL_WEB_SERVER_SIMULATION:URL_WEB_SERVER, 
            simulate?PORT_WEB_SERVER_SIMULATION:PORT_WEB_SERVER);
        System.out.println("HTTP-Forwarding: Created socket "+socketForwardingWebapp.getInetAddress()+":"+socketForwardingWebapp.getPort());  
        InputStream webappInputStream = socketForwardingWebapp.getInputStream();
        OutputStream outputStream = socketForwardingWebapp.getOutputStream();
        if(incomingRequest.available()>0){
            System.out.println("Incoming Request can be forwarded");
            long bytesTransfered = incomingRequest.transferTo(outputStream);
            System.out.print("stream copied");
            socketForwardingWebapp.shutdownOutput();
            System.out.println("Bytes forwareded: "+bytesTransfered);
        }
        return webappInputStream;
    }catch(Exception exc){
        exc.printStackTrace();
    }
    return null;
}

I solved this problem using Threads.我使用线程解决了这个问题。 Here is what worked:这是有效的:

    private static Thread inputStreamToOutputStream(InputStream inputStream, OutputStream outputStream){
    Thread t = new Thread(() -> {
        long transferedBytes = 0;
        try {
            transferedBytes = inputStream.transferTo(outputStream);
            inputStream.close();
            outputStream.close();
            System.out.println("StreamTransformer: Bytes forwareded: "+transferedBytes);
        } catch (IOException e) {
            System.out.println("StreamTransformer: Error accoured while transforming");
        }
    });
    t.start();
    return t;
}

Used this new method like this:像这样使用这种新方法:

private static Thread sendHttpRequestToDestination(InputStream incomingRequest, OutputStream outgoingAnswer, Boolean simulate){
    Thread t = new Thread(){
        public void run(){
            try{  
                Socket socketForwardingWebapp = new Socket(simulate?URL_WEB_SERVER_SIMULATION:URL_WEB_SERVER, 
                    simulate?PORT_WEB_SERVER_SIMULATION:PORT_WEB_SERVER);
                System.out.println("HTTP-Forwarding: Created socket "+socketForwardingWebapp.getInetAddress()+":"+socketForwardingWebapp.getPort());  
                InputStream webappInputStream = socketForwardingWebapp.getInputStream();
                OutputStream outputStream = socketForwardingWebapp.getOutputStream();
                if(incomingRequest.available()>0){
                    System.out.println("HTTP-Forwarding: Incoming Request can be forwarded");
                    Thread send = inputStreamToOutputStream(incomingRequest, outputStream);
                    Thread receive = inputStreamToOutputStream(webappInputStream, outgoingAnswer);
                    send.join();
                    System.out.println("HTTP-Forwarding: successfuly sent");
                    receive.join();
                    System.out.println("HTTP-Forwarding: successfuly received");
                }
                socketForwardingWebapp.close();
            }catch(Exception exc){
                exc.printStackTrace();
            }
        }
    };
    t.start();
    return t;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM