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

The following examples show how to use org.apache.mina.transport.socket.nio.NioSocketAcceptor#setReuseAddress() . 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: 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 3
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 4
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 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: 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 7
Source File: MINAConnectionAcceptor.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private static NioSocketAcceptor buildSocketAcceptor()
{
    // Create SocketAcceptor with correct number of processors
    final int processorCount = JiveGlobals.getIntProperty( "xmpp.processor.count", Runtime.getRuntime().availableProcessors() );

    final NioSocketAcceptor socketAcceptor = new NioSocketAcceptor( processorCount );

    // Set that it will be possible to bind a socket if there is a connection in the timeout state.
    socketAcceptor.setReuseAddress( true );

    // Set the listen backlog (queue) length. Default is 50.
    socketAcceptor.setBacklog( JiveGlobals.getIntProperty( "xmpp.socket.backlog", 50 ) );

    // Set default (low level) settings for new socket connections
    final SocketSessionConfig socketSessionConfig = socketAcceptor.getSessionConfig();

    //socketSessionConfig.setKeepAlive();
    final int receiveBuffer = JiveGlobals.getIntProperty( "xmpp.socket.buffer.receive", -1 );
    if ( receiveBuffer > 0 )
    {
        socketSessionConfig.setReceiveBufferSize( receiveBuffer );
    }

    final int sendBuffer = JiveGlobals.getIntProperty( "xmpp.socket.buffer.send", -1 );
    if ( sendBuffer > 0 )
    {
        socketSessionConfig.setSendBufferSize( sendBuffer );
    }

    final int linger = JiveGlobals.getIntProperty( "xmpp.socket.linger", -1 );
    if ( linger > 0 )
    {
        socketSessionConfig.setSoLinger( linger );
    }

    socketSessionConfig.setTcpNoDelay( JiveGlobals.getBooleanProperty( "xmpp.socket.tcp-nodelay", socketSessionConfig.isTcpNoDelay() ) );

    return socketAcceptor;
}
 
Example 8
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 9
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;
}