package de.rub.nds.socketproxy;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by xinz on 17/4/5.
*/
public class TcpProxy1 {
public String proxyAddress;
public int proxyPort;
public int sourcePort;
/**
* 命令参考:java -jar SocketProxy-1.0-SNAPSHOT-jar-with-dependencies1.jar 10.16.66.201 11000 9888
* 三个参数:目标服务器地址 代理端口 目标服务器端口
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
if(args == null || args.length != 3){
System.out.println("args format:proxyAddress proxyPort sourcePort");
System.exit(-1);
}
TcpProxy1 tcpProxy = new TcpProxy1(args[0],Integer.valueOf(args[1]),Integer.valueOf(args[2]));
tcpProxy.start();
}
public TcpProxy1(String proxyAddress, int proxyPort, int sourcePort){
this.proxyAddress = proxyAddress;
this.proxyPort= proxyPort;
this.sourcePort = sourcePort;
}
public void start() throws IOException {
ServerSocket server = new ServerSocket(sourcePort);
while(true){
Socket socket = server.accept();
InputStream clientIn = socket.getInputStream();
OutputStream clientOut = socket.getOutputStream();
Socket proxysocket = new Socket(proxyAddress,proxyPort);
InputStream proxyIn = proxysocket.getInputStream();
OutputStream proxyOut = proxysocket.getOutputStream();
Thread taskSend = new Thread(new Task(clientIn,proxyOut));
Thread taskRecieve = new Thread(new Task(proxyIn,clientOut));
System.out.println("[" + taskSend.getId() + "]Thread Read");
System.out.println("[" + taskRecieve.getId() + "]Thread Write");
taskSend.start();
taskRecieve.start();
}
}
class Task implements Runnable {
InputStream inputStream;
OutputStream outputStream;
public Task(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public void run() {
try {
byte[] data = new byte[1500];
while (true) {
int rs = inputStream.read(data);
if(rs == -1){
break;
}
outputStream.write(data,0,rs);
outputStream.flush();
System.out.println("[" + Thread.currentThread().getId() + "]dataSize " + rs);
}
System.out.println("["+Thread.currentThread().getId()+"]finish");
} catch (Throwable throwable) {
System.out.println("["+Thread.currentThread().getId()+"]Exception:");
throwable.printStackTrace();
}finally {
try {
if(null != inputStream)
inputStream.close();
if(null != outputStream)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>de.rub.nds.socketproxy.TcpProxy1</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>