java版tcp proxy

 
 
package com.xiaomi.dbproxy.action;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.xiaomi.dbproxy.model.proxyServer;
import com.xiaomi.dbproxy.model.proxyService;
import com.xiaomi.dbproxy.tools.Log;

public class tcpProxy implements Runnable {
	proxyServer server;
	Random rand = new Random(new Date().getTime());
	public tcpProxy(){}

	public tcpProxy(proxyServer server) {
		this.server = server;
	}
	public static Socket getSocket(List<proxyService> list){
		Socket outgoing = null;
		for(proxyService item : list){
			try{
				if(item.cantry()){
				outgoing = new Socket(item.getHost(), item.getPort());
				}else{
					continue;
				}
				return outgoing;
			}catch(Exception e){
				item.setEcount();
				continue;
			}
		}
		return null;
	}
	@Override
	public void run() {
		ServerSocket ss = null;
		Socket incoming, outgoing = null;
		try {
			ss = new ServerSocket(this.server.getPort());
		} catch (Exception e) {
			Log.logError(e);
		}
		int index = 0;
		int len = this.server.getList().size();
		while (true) {
			try {
				incoming = ss.accept();
				proxyService ps = this.server.getList().get(index);
				try{
					if(ps.cantry()){
						outgoing = new Socket(ps.getHost(), ps.getPort());
					}else{
						outgoing = tcpProxy.getSocket(this.server.getList());
					}
				}catch(Exception ex){
					ps.setEcount();
					outgoing = tcpProxy.getSocket(this.server.getList());
				}
				
				if(outgoing==null||!outgoing.isConnected()){
					throw new Exception("server: "+this.server.getPort()+" can't connect service");
				}
				
				proxyThread thread1 = new proxyThread(incoming, outgoing);
				proxyThread thread2 = new proxyThread(outgoing, incoming);
				thread1.start();
				thread2.start();
			} catch (Exception e) {
				Log.logError(e);
			}finally{
				index++;
				if(index>=len){
					index=0;
				}
			}
		}
	}

	public proxyServer getServer() {
		return server;
	}

	public void setServer(proxyServer server) {
		this.server = server;
	}
}

package com.xiaomi.dbproxy.action;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.xiaomi.dbproxy.tools.Log;
import com.xiaomi.dbproxy.tools.proxyConfig;

public class proxyThread extends Thread {
	Socket incoming, outgoing;
	
	public proxyThread(Socket in, Socket out) {
		incoming = in;
		outgoing = out;
	}

	public void run() {
		byte[] buffer = new byte[proxyConfig.IO_BUFFER];
		int numberRead = 0;
		OutputStream ToClient;
		InputStream FromClient;

		try {
			ToClient = outgoing.getOutputStream();
			FromClient = incoming.getInputStream();
			while (true) {
				numberRead = FromClient.read(buffer, 0, proxyConfig.IO_BUFFER);

				if (numberRead == -1) {
					incoming.close();
					outgoing.close();
				}

				ToClient.write(buffer, 0, numberRead);
			}
		} catch (Exception e) {
			Log.logError(e);
		}
	}
}


你可能感兴趣的:(java版tcp proxy)