package org.kne.cloud.network;

import java.io.IOException;
import java.net.*;

public class PortRelay {
	private int port;
	private HostPortMap services;
	private SocketListener ssc;
	public PortRelay(int port, HostPortMap services) throws IOException {
		this.services = services;
		this.port = port;
		MultiProtocolSocketAddress.getSocketTypeRegister().put("ProtocolDetectorServerSocket",new SocketType(null, new ProtocolDetectorServerSocketFactory()) );
	ssc=new SocketListener(new MultiProtocolSocketAddress("ProtocolDetectorServerSocket", "0.0.0.0", port));
	}
	public void start() throws IOException {
		ssc.setCon((s)->{
			
			Socket sl = null;
			ProtocolDetectorSocket pds=(ProtocolDetectorSocket) s;
			String nx;
			if(pds.getProtocolStack().isEmpty()) {
				nx="DEFAULT";
			}else {
				nx=pds.getProtocolStack().pop().getName();
			}
			MultiProtocolSocketAddress hp=services.get(nx);
			InetSocketAddress sa=(InetSocketAddress) s.getRemoteSocketAddress();
			System.out.println(sa.getAddress().getHostAddress() + ":" + port
					+ "-" + "(" + nx + ")->" + hp.getHost() + ":" + hp.getPort());
			try {
				sl=hp.connectSocket();
				s.setSoTimeout(120*60*1000);
				sl.setSoTimeout(120*60*1000);
			new SocketBridge(s, sl).run();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if(sl!=null)
					sl.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					pds.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		});
		System.out.println("已打开端口：" + port);
	}
	
}
