1 package org.wamblee.socketproxy;
4 * Created on Apr 5, 2005
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.net.ServerSocket;
11 import java.net.Socket;
16 * TODO To change the template for this generated type comment go to Window -
17 * Preferences - Java - Code Style - Code Templates
19 public class SocketProxy {
21 public static void main( final String[] args ) throws IOException {
22 for ( int i = 0; i < args.length; i++ ) {
23 // System.out.println(i + " " + args[i]);
24 String[] fields = args[i].split( ":" );
25 final int localPort = Integer.parseInt( fields[0] );
26 final String host = fields[1];
27 final int remotePort = Integer.parseInt( fields[2] );
28 runSocketProxy( localPort, host, remotePort );
37 private static void runSocketProxy( final int localPort,
38 final String host, final int remotePort ) {
39 new Thread( new Runnable( ) {
42 new SocketProxy( localPort, host, remotePort );
43 } catch ( IOException e ) {
44 System.out.println( "Problem with socket " + localPort
45 + ":" + host + ":" + remotePort );
52 public SocketProxy( int localPort, String remoteHost, int remotePort )
54 System.out.println( "Listening on port " + localPort );
55 ServerSocket server = new ServerSocket( localPort );
57 Socket socket = server.accept( );
58 System.out.println( "Got local connection on port "
60 InputStream localIs = socket.getInputStream( );
61 OutputStream localOs = socket.getOutputStream( );
62 Socket clientSocket = new Socket( remoteHost, remotePort );
63 final String description = "Port forwarding: " + localPort
64 + " -> " + remoteHost + ":" + remotePort;
65 System.out.println( description + " established." );
66 InputStream serverIs = clientSocket.getInputStream( );
67 OutputStream serverOs = clientSocket.getOutputStream( );
68 Barrier barrier = new Barrier(2);
69 final Thread t1 = runForwarder( barrier, "> ", localIs, serverOs );
70 final Thread t2 = runForwarder( barrier, "< ", serverIs, localOs );
71 waitForConnectionClose( description, t1, t2 );
80 private void waitForConnectionClose( final String description,
81 final Thread t1, final Thread t2 ) {
82 new Thread( new Runnable( ) {
87 } catch ( InterruptedException e ) {
90 System.out.println( description + " closed" );
95 private Thread runForwarder( final Barrier barrier, final String prefix,
96 final InputStream is, final OutputStream os ) {
97 Thread t = new ForwarderThread(prefix, barrier, is, os);