java 代码实现 lcx 端口转发例子

完整示例:

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Lcx {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("lcx 127.0.0.1 5555 127.0.0.1 8888");
		for (String string : args) {
			System.out.println(string);
		}

		/*
		 * lcx 127.0.0.1 5555 127.0.0.1 8888
		 */

		String listenerAddress = args[0];

		int listenerPort = Integer.parseInt(args[1]);
		String connectAddress = args[2];
		int connectPort = Integer.parseInt(args[3]);

		try {
			ServerSocket serverSocket = new ServerSocket(listenerPort, 50, InetAddress.getByName(listenerAddress));
			System.out.println("监听中...");
			while (true) {
				Socket accept = serverSocket.accept();
				System.out.println("已连接:" + accept.getInetAddress().toString());
				try {
					Socket socket = new Socket(connectAddress, connectPort);
					new Thread(new PipeStream(accept, socket)).start();
					new Thread(new PipeStream(socket, accept)).start();
				} catch (Exception e) {
					System.out.println(connectAddress + ":" + connectPort + "连接失败..");
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static class PipeStream implements Runnable {
		private Socket inx, outx;

		public PipeStream(Socket inx, Socket outx) {
			this.inx = inx;
			this.outx = outx;
		}

		@Override
		public void run() {
			try {
				BufferedInputStream bufferedInputStream = new BufferedInputStream(inx.getInputStream());
				BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outx.getOutputStream());
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = bufferedInputStream.read(bytes)) > 0) {
					bufferedOutputStream.write(bytes, 0, len);
					bufferedOutputStream.flush();
				}
				System.out.println(inx.getInetAddress().toString() + " 退出连接...");
				bufferedInputStream.close();
				bufferedOutputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (!inx.isClosed())
					try {
						inx.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				if (!outx.isClosed())
					try {
						outx.close();
						System.out.println("退出成功!");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		}

	}
}

 

你可能感兴趣的:(Java)