Java Code Examples for org.apache.mina.transport.socket.nio.NioSocketAcceptor#bind()

The following examples show how to use org.apache.mina.transport.socket.nio.NioSocketAcceptor#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Server.java    From oim-fx with MIT License 6 votes vote down vote up
public synchronized boolean startServer(int port) {
    if (running) {
        return running;
    }
    try {

        acceptor = new NioSocketAcceptor();
        acceptor.addListener(new ServerListener());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new DataCodecFactory()));
        acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
        acceptor.getSessionConfig().setReadBufferSize(2048); // 设置读取数据的缓冲区大小
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 读写通道10秒内无操作进入空闲状态
        acceptor.setHandler(new ServerHandler()); // 绑定逻辑处理起器
        acceptor.bind(new InetSocketAddress(port));// 绑定端口
        acceptor.setReuseAddress(true);
        logger.info("服务器启动成功。。。。端口为:" + port);
        return running = true;
    } catch (IOException e) {
        logger.error("服务器启动异常。。。。", e);
        e.printStackTrace();
        running = false;
    }
    return running = false;
}
 
Example 2
Source File: MinaRemotingServer.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
@Override
protected void serverStart() throws RemotingException {

    acceptor = new NioSocketAcceptor(); //TCP Acceptor

    // acceptor.getFilterChain().addFirst("logging", new MinaLoggingFilter());
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecFactory(getCodec())));
    acceptor.getFilterChain().addLast("mdc", new MdcInjectionFilter());

    acceptor.setHandler(new MinaHandler(this));
    IoSessionConfig cfg = acceptor.getSessionConfig();
    cfg.setReaderIdleTime(remotingServerConfig.getReaderIdleTimeSeconds());
    cfg.setWriterIdleTime(remotingServerConfig.getWriterIdleTimeSeconds());
    cfg.setBothIdleTime(remotingServerConfig.getServerChannelMaxIdleTimeSeconds());

    bindAddress = new InetSocketAddress(remotingServerConfig.getListenPort());
    try {
        acceptor.bind(bindAddress);
    } catch (IOException e) {
        throw new RemotingException("Start Mina server error", e);
    }
}
 
Example 3
Source File: CrossServer.java    From jforgame with Apache License 2.0 6 votes vote down vote up
/**
 * start Mina serversocket
 * @throws Exception
 */
@Override
public void start() throws Exception {
	final int serverPort = ServerConfig.getInstance().getCrossPort();
	IoBuffer.setUseDirectBuffer(false);
	IoBuffer.setAllocator(new SimpleBufferAllocator());

	acceptor = new NioSocketAcceptor(pool);
	acceptor.setReuseAddress(true);
	acceptor.getSessionConfig().setAll(getSessionConfig());

	logger.info("cross server start at port:{},正在监听服务器点对点的连接...", serverPort);
	DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
	filterChain.addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	//指定业务逻辑处理器
	acceptor.setHandler(new Game2GameIoHandler(BaseCrossMessageDispatcher.getInstance()));
	//设置端口号
	acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort));
	//启动监听
	acceptor.bind();
}
 
Example 4
Source File: MinaSocketServer.java    From jforgame with Apache License 2.0 6 votes vote down vote up
/**
 * start Mina serversocket
 * @throws Exception
 */
@Override
public void start() throws Exception {
	int serverPort = ServerConfig.getInstance().getServerPort();
	IoBuffer.setUseDirectBuffer(false);
	IoBuffer.setAllocator(new SimpleBufferAllocator());

	acceptor = new NioSocketAcceptor(pool);
	acceptor.setReuseAddress(true);
	acceptor.getSessionConfig().setAll(getSessionConfig());

	logger.info("mina socket server start at port:{},正在监听客户端的连接...", serverPort);
	DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
	filterChain.addLast("codec",
			new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory()));
	filterChain.addLast("moduleEntrance", new ModuleEntranceFilter());
	filterChain.addLast("msgTrace", new MessageTraceFilter());
	filterChain.addLast("flood", new FloodFilter());
	//指定业务逻辑处理器
	acceptor.setHandler(new ServerSocketIoHandler(new MessageDispatcher()));
	//设置端口号
	acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort));
	//启动监听
	acceptor.bind();
}
 
Example 5
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new WebSocketCodecFactory()));
    // close sessions when the acceptor is stopped
    acceptor.setCloseOnDeactivation(true);
    acceptor.setHandler(new WebSocketHandler());
    SocketSessionConfig sessionConf = acceptor.getSessionConfig();
    sessionConf.setReuseAddress(true);
    acceptor.setReuseAddress(true);
    // loop through the addresses and bind
    Set<InetSocketAddress> socketAddresses = new HashSet<InetSocketAddress>();
    socketAddresses.add(new InetSocketAddress("0.0.0.0", 8888));
    //socketAddresses.add(new InetSocketAddress("localhost", 8888));
    log.debug("Binding to {}", socketAddresses.toString());
    acceptor.bind(socketAddresses);
    System.out.println("WS server started listening");
    listening = true;
    while (true) {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            System.out.println("WS server stopped listening");
        }
    }
}
 
Example 6
Source File: NetManager.java    From GameServer with Apache License 2.0 6 votes vote down vote up
public  void startListner(IoHandler iohandler,int listenPort) throws Exception{
	acceptor = new NioSocketAcceptor();
	acceptor.setBacklog(100);
	acceptor.setReuseAddress(true);
	acceptor.setHandler(iohandler);
	
       DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
       IoFilter protocol = new ProtocolCodecFilter(new GameProtocolcodecFactory());
       chain.addLast("codec", protocol);
	threadpool = new OrderedThreadPoolExecutor(500);
	threadpool.setThreadFactory(new ServerThreadFactory("OrderedThreadPool"));
	chain.addLast("threadPool", new ExecutorFilter(threadpool));
	
	int recsize = 5120;
	int sendsize = 40480;                                                                                         
	int timeout = 10;
	SocketSessionConfig sc = acceptor.getSessionConfig();
	sc.setReuseAddress(true);// 设置每一个非主监听连接的端口可以重用
	sc.setReceiveBufferSize(recsize);// 设置输入缓冲区的大小
	sc.setSendBufferSize(sendsize);// 设置输出缓冲区的大小
	sc.setTcpNoDelay(true);// flush函数的调用 设置为非延迟发送,为true则不组装成大包发送,收到东西马上发出   
	sc.setSoLinger(0);
	sc.setIdleTime(IdleStatus.READER_IDLE, timeout);
	acceptor.bind(new InetSocketAddress(listenPort));
}
 
Example 7
Source File: CashShopServer.java    From mapleLemon with GNU General Public License v2.0 6 votes vote down vote up
public static void run_startup_configurations() {
    autoPaoDian = Integer.parseInt(ServerProperties.getProperty("autoPaoDian", "1"));
    port = Short.parseShort(ServerProperties.getProperty("cashshop.port", String.valueOf(DEFAULT_PORT)));
    ip = ServerProperties.getProperty("world.host", ServerConstants.IP) + ":" + port;

    IoBuffer.setUseDirectBuffer(false);
    IoBuffer.setAllocator(new SimpleBufferAllocator());

    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
    players = new PlayerStorage(MapleServerHandler.CASH_SHOP_SERVER);
    try {
        acceptor.setHandler(new MapleServerHandler(MapleServerHandler.CASH_SHOP_SERVER));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);

        FileoutputUtil.log("完成!");
        FileoutputUtil.log("商城伺服器正在监听" + port + "端口\r\n");
    } catch (IOException e) {
        FileoutputUtil.log("失败!");
        System.err.println("无法绑定" + port + "端口");
        throw new RuntimeException("绑定端口失败.", e);
    }
}
 
Example 8
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 6 votes vote down vote up
private void bindWebPort() throws IOException {

		/*
		 * 预制websocket握手请求的处理
		 */
		INNER_HANDLER_MAP.put(CIMConstant.CLIENT_WEBSOCKET_HANDSHAKE, new WebsocketHandler());

		webAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setTcpNoDelay(true);
		webAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebMessageCodecFactory()));
		webAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		webAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		webAcceptor.setHandler(this);

		webAcceptor.bind(new InetSocketAddress(webPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   Websocket Server started on port {}.                         *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, webPort);
	}
 
Example 9
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 5 votes vote down vote up
private void bindAppPort() throws IOException {


		appAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setTcpNoDelay(true);

		KeepAliveFilter keepAliveFilter = new KeepAliveFilter(this, IdleStatus.BOTH_IDLE);
		keepAliveFilter.setRequestInterval(IDLE_HEART_REQUEST_TIME);
		keepAliveFilter.setRequestTimeout(HEART_RESPONSE_TIME_OUT);
		keepAliveFilter.setForwardEvent(true);

		appAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new AppMessageCodecFactory()));
		appAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		appAcceptor.getFilterChain().addLast("heartbeat", keepAliveFilter);
		appAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		appAcceptor.setHandler(this);

		appAcceptor.bind(new InetSocketAddress(appPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   App Socket Server started on port {}.                        *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, appPort);
	}
 
Example 10
Source File: Server111.java    From MiniWeChat-Server with MIT License 5 votes vote down vote up
public Server111(){
	// 显示IP地址
			InetAddress addr;
			try {
				addr = InetAddress.getLocalHost();
				Debug.log("IP address:" + addr.getHostAddress().toString());
				Debug.log("Host Name:" + addr.getHostName().toString());
				// logger.debug("IP地址:"+addr.getHostAddress().toString());
				// logger.debug("本机名称:"+ addr.getHostName().toString());

			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			}
			Debug.log("Port Number:8081");
			// logger.debug("端口号:8081");

			acceptor = new NioSocketAcceptor();
			// 指定编码解码器
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
			acceptor.setHandler(this);
			try {
				acceptor.bind(new InetSocketAddress(8081));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
}
 
Example 11
Source File: MinaNetServer.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void start() {
    if (isStarted())
        return;
    logger.info("Starting mina net server");
    try {
        acceptor = new NioSocketAcceptor();
        // DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        acceptor.setHandler(new MinaNetServerHandler(this));
        acceptor.bind(new InetSocketAddress(getHost(), getPort()));
        super.start();
    } catch (Exception e) {
        checkBindException(e, "Failed to start mina net server");
    }
}
 
Example 12
Source File: ConsoleServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() throws IOException {
	acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("codec",
			new ProtocolCodecFilter(new TextLineCodecFactory(MTGConstants.DEFAULT_ENCODING)));
	acceptor.getSessionConfig().setReadBufferSize(getInt("BUFFER-SIZE"));
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, getInt("IDLE-TIME"));
	MTGConsoleHandler handler = new MTGConsoleHandler();
	handler.setWelcomeMessage(getString("STARTUP_MESSAGE"));
	acceptor.setHandler(handler);
	acceptor.bind(new InetSocketAddress(getInt(SERVER_PORT)));
	logger.info("Server started on port " + getString(SERVER_PORT));
}
 
Example 13
Source File: MinaStartup.java    From seed with Apache License 2.0 5 votes vote down vote up
public final void bind() throws IOException {
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    //这里并未配置backlog,那么它会采用操作系统默认的连接请求队列长度50
    //详见org.apache.mina.core.polling.AbstractPollingIoAcceptor类源码的96行
    //acceptor.setBacklog(0);
    acceptor.setReuseAddress(this.reuseAddress);
    acceptor.getSessionConfig().setWriteTimeout(this.writeTimeout);
    acceptor.getSessionConfig().setBothIdleTime(this.bothIdleTime);
    //这里有个鱼和熊掌不可兼得的情景
    //若将codec定义在executor的前面,则codec由NioProcessor-1线程处理,IoHandler由pool-1-thread-1线程处理
    //若将codec定义在executor的后面,则codec和IoHandler都由pool-1-thread-1线程处理
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ServerProtocolCodecFactory()));
    acceptor.getFilterChain().addLast("executor", new ExecutorFilter());
    //注意:无论如何executor都要定义在NioSocketConnector.setHandler()的前面
    acceptor.setHandler(this.handler);
    if(null==this.socketAddresses || this.socketAddresses.size()<1){
        throw new RuntimeException("监听SocketAddress数不得小于1");
    }
    acceptor.bind(this.socketAddresses);
    if(acceptor.isActive()){
        System.out.println("写 超 时: " + this.writeTimeout + "ms");
        System.out.println("发呆配置: Both Idle " + this.bothIdleTime + "s");
        System.out.println("端口重用: " + this.reuseAddress);
        System.out.println("服务端初始化完成...");
        System.out.println("服务已启动...开始监听..." + acceptor.getLocalAddresses());
    }else{
        System.out.println("服务端初始化失败...");
    }
}
 
Example 14
Source File: MatchServer.java    From jforgame with Apache License 2.0 5 votes vote down vote up
public void start(int port) throws Exception {
	this.port = port;
	acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("codec", new HttpServerCodec());
	acceptor.setHandler(new HttpServerHandle());

	acceptor.bind(new InetSocketAddress(port));

	logger.error("---------> http server start at port:{}", port);
}
 
Example 15
Source File: HttpServer.java    From jforgame with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
	acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("codec", new HttpServerCodec());
	acceptor.setHandler(new HttpServerHandle());

	ServerConfig serverConfig = ServerConfig.getInstance();
	this.port = serverConfig.getHttpPort();
	acceptor.bind(new InetSocketAddress(port));
}
 
Example 16
Source File: ServerNetwork.java    From MiniWeChat-Server with MIT License 4 votes vote down vote up
/**
	 * 初始化
	 * 
	 * @throws IOException
	 * @author Feng
	 */
	public void init() {
		if (addr != null || minaServerHandle == null)
			return;

		// 显示IP地址
		try {
			addr = InetAddress.getLocalHost();
			logger.info("IP address:" + addr.getHostAddress().toString());
			logger.info("Host Name:" + addr.getHostName().toString());

		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		// Debug.log("Port Number:8081");
		logger.debug("Port Number:8081");

		acceptor = new NioSocketAcceptor();
		// 指定编码解码器
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
//		System.out.println("22222222222222222222222222");
		if (myLogger == null)
			myLogger = new MyLogger();
//		System.out.println(myLogger == null);
		acceptor.getFilterChain().addLast("Logger", myLogger);
		// System.out.println("codec " + (protocolCodecFilter == null));
		// acceptor.getFilterChain().addLast("codec", protocolCodecFilter);
		acceptor.getSessionConfig().setMaxReadBufferSize(1024 * 8);
		// System.out.println("minaServerHandle :" + (minaServerHandle ==
		// null));
		acceptor.setHandler(minaServerHandle);
		// acceptor.setHandler(new MinaServerHandle());
		try {
			acceptor.bind(new InetSocketAddress(8081));
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("ServerNetwork : Acceptor bind Exception!;\n" + e.toString());
		}

		// new ClassPathXmlApplicationContext("trapReceiverContext.xml");
	}
 
Example 17
Source File: Channel.java    From HeavenMS with GNU Affero General Public License v3.0 4 votes vote down vote up
public Channel(final int world, final int channel, long startTime) {
    this.world = world;
    this.channel = channel;
    
    this.ongoingStartTime = startTime + 10000;  // rude approach to a world's last channel boot time, placeholder for the 1st wedding reservation ever
    this.mapManager = new MapleMapManager(null, world, channel);
    try {
        port = 7575 + this.channel - 1;
        port += (world * 100);
        ip = YamlConfig.config.server.HOST + ":" + port;
        IoBuffer.setUseDirectBuffer(false);
        IoBuffer.setAllocator(new SimpleBufferAllocator());
        acceptor = new NioSocketAcceptor();
        acceptor.setHandler(new MapleServerHandler(world, channel));
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
        acceptor.getFilterChain().addLast("codec", (IoFilter) new ProtocolCodecFilter(new MapleCodecFactory()));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);
        for (MapleExpeditionType exped : MapleExpeditionType.values()) {
        	expedType.add(exped);
        }
        
        if (Server.getInstance().isOnline()) {  // postpone event loading to improve boot time... thanks Riizade, daronhudson for noticing slow startup times
            eventSM = new EventScriptManager(this, getEvents());
            eventSM.init();
        } else {
            String[] ev = {"0_EXAMPLE"};
            eventSM = new EventScriptManager(this, ev);
        }
        
        dojoStage = new int[20];
        dojoFinishTime = new long[20];
        dojoTask = new ScheduledFuture<?>[20];
        for(int i = 0; i < 20; i++) {
            dojoStage[i] = 0;
            dojoFinishTime[i] = 0;
            dojoTask[i] = null;
        }
        
        services = new ServicesManager(ChannelServices.OVERALL);
        
        System.out.println("    Channel " + getId() + ": Listening on port " + port);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example 19
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example 20
Source File: MinaServer.java    From grain with MIT License 3 votes vote down vote up
/**
 * 初始化tcp服务器
 * 
 * @param ip
 *            监听ip 0.0.0.0最好
 * @param port
 *            监听端口
 * @param HandlerClass
 *            继承MinaHandler的类
 * @param useTcpMonitor
 *            是否输出监控日志
 * @param log
 *            日志可以为null
 * @throws Throwable
 */
public static void init(String ip, int port, Class<?> HandlerClass, boolean useTcpMonitor, ILog log) throws Exception {
	MinaConfig.USE_TCP_MONITOR = useTcpMonitor;
	MinaConfig.log = log;
	// 初始化
	ioAcceptor = new NioSocketAcceptor();
	// 设置编码解码
	ioAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
	// 设置处理函数实现IoHandler接口
	MinaHandler minaHandler = (MinaHandler) HandlerClass.newInstance();
	ioAcceptor.setHandler(minaHandler);
	// 绑定ip地址与端口
	ioAcceptor.bind(new InetSocketAddress(ip, port));
}