I have a Java program that mirrors a connection from a client server to a remote server. The mirror send data find, but does not receive. I cannot for the life of me figure out why. Here is my code:
Socket client = new Socket("127.0.0.1", 42001);
System.out.println("Connected to client!");
Socket server = new Socket(serverAddress, serverPort);
System.out.println("Connected to server!");
BufferedReader clientin = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter scratchout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader serverin = new BufferedReader(new InputStreamReader(server.getInputStream()));
BufferedWriter serverout = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
int i;
boolean serverNeedsFlush = false;
boolean clientNeedsFlush = false;
while (true)
{
while (clientin.ready())
{
i = clientin.read();
serverout.write(i);
serverNeedsFlush = true;
}
if(serverNeedsFlush)
{
serverout.flush();
serverNeedsFlush = false;
}
while (serverin.ready())
{
i = serverin.read();
System.out.print((char)i);
scratchout.write(i);
clientNeedsFlush = true;
}
if(clientNeedsFlush)
{
scratchout.flush();
clientNeedsFlush = false;
}
}
If your trying to forward data from one socket to another it would probably be a better idea to use the socket streams directly rather than decorating them.
As other posters have suggested you should use threads to do this. It will make life easier. You can then use the threads to do a basic in to out stream copy like below.
When the method above returns you will have read the entire
instream and written it in to theoutstream. Your run method for your thread or runnable could look something like this.