package com.acme.example; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPRepeater { public static final int PORT = 5001; public static final String REDIRECT_HOST = "192.168.254.40"; public static final int REDIRECT_PORT = 5001; public static void main(String[] args) { TCPRepeater t = new TCPRepeater(); t.test(); } public void test() { try { ServerSocket serverSocket = new ServerSocket(PORT); Socket src = serverSocket.accept(); Socket dst = new Socket(REDIRECT_HOST,REDIRECT_PORT); Repeater r = new Repeater(src, dst); r.go(); } catch (Exception e) { e.printStackTrace(); } } static class Repeater { Socket srcSocket; Socket dstSocket; public Repeater(Socket srcSocket, Socket destSocket) { super(); this.srcSocket = srcSocket; this.dstSocket = destSocket; } // TODO: Name the repeater threads public void go() throws IOException, InterruptedException { StreamRepeater srcRepeater = new StreamRepeater( "rpt-in", srcSocket.getInputStream(), dstSocket.getOutputStream()); StreamRepeater dstRepeater = new StreamRepeater( "rpt-out", dstSocket.getInputStream(), srcSocket.getOutputStream()); srcRepeater.start(); dstRepeater.start(); System.out.println("Repeaters started"); srcRepeater.join(); dstRepeater.join(); System.out.println("Repeaters finished"); } } static class StreamRepeater extends Thread { InputStream srcStream; OutputStream dstStream; public StreamRepeater(String name, InputStream srcStream, OutputStream dstStream) { super(name); this.srcStream = srcStream; this.dstStream = dstStream; } public void run() { try { byte[] buff = new byte[32768]; int c; while ((c = srcStream.read(buff)) != -1) { dstStream.write(buff,0,c); } srcStream.close(); dstStream.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Repeater finished"); } } }