1 4 package com.tc.network; 5 6 import com.tc.net.proxy.TCPProxy; 7 import com.tc.util.Assert; 8 9 import java.io.IOException ; 10 import java.net.InetAddress ; 11 import java.net.InetSocketAddress ; 12 import java.net.Socket ; 13 import java.net.UnknownHostException ; 14 15 public final class TCPProxyFixture { 16 17 private final TCPProxy proxy; 18 private final int localPort; 19 private boolean up; 20 21 25 public TCPProxyFixture(String remoteHost, int remotePort) throws UnknownHostException { 26 Assert.assertNotNull(remoteHost); 27 localPort = findAvailableLocalPort(); 28 proxy = new TCPProxy(localPort, InetAddress.getByName(remoteHost), remotePort, 0, false, null); 29 up = false; 30 } 31 32 public int localPort() { 33 return localPort; 34 } 35 36 public synchronized void severeConnection() { 37 Assert.eval("Connection must be started in order to severe it", up); 38 proxy.stop(); 39 up = false; 40 } 41 42 public synchronized void establishConnection() throws IOException { 43 Assert.eval("Connection must be stopped to start it", !up); 44 proxy.start(); 45 up = true; 46 } 47 48 private static int findAvailableLocalPort() { 49 int port = 18456; 50 while (true) { 51 Socket socket = new Socket (); 52 try { 53 socket.connect(new InetSocketAddress (port)); 54 socket.close(); 56 ++port; 57 } catch (IOException e) { 58 break; 60 } 61 } 62 return port; 63 } 64 65 } 66 | Popular Tags |