Home > Software engineering >  Redirect Socket Inputstream to Outputstream from another socket
Redirect Socket Inputstream to Outputstream from another socket

Time:08-27

im trying to listen on HTTP requests for an website in my application. 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). The webserver should anser (->Inputstream2) and i want to pass it back to outputstream1 of socket1. 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.

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;
}

CodePudding user response:

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;
}
  • Related