org.apache.mina.transport.socket.nio.NioSocketAcceptor Java Examples

The following examples show how to use org.apache.mina.transport.socket.nio.NioSocketAcceptor. 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: 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 #2
Source File: CalculatorServer.java    From mina with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
        IoAcceptor acceptor = new NioSocketAcceptor();
//        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDELTIMEOUT);

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("myfliter", new MyFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8")));

        KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl();
        KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.BOTH_IDLE);
        /** 是否回发 */
        kaf.setForwardEvent(true);
        acceptor.getFilterChain().addLast("heart", kaf);

        acceptor.setHandler(new CalculatorHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        log.debug("socket通信服务端已启动,端口是" + PORT);
    }
 
Example #3
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 #4
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 #5
Source File: TCPTestServer.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the MINA server.
 */
public TCPTestServer(int port, boolean loopback, IoHandler handler) throws Exception {

    acceptor = new NioSocketAcceptor();

    IoFilter tupleEncoder = new ProtocolCodecFilter(new TestTupleEncoder(),
            new TestTupleDecoder());

    acceptor.getFilterChain().addLast("testtuples", tupleEncoder);

    acceptor.setHandler(handler);

    // Get the bind address now so the majority of
    // errors are caught at initialization time.
    bindAddress = new InetSocketAddress(
            loopback ? InetAddress.getLoopbackAddress() : InetAddress.getLocalHost(), port);
}
 
Example #6
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 #7
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 #8
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 #9
Source File: MinaTimeServer.java    From java-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 创建服务器端的监听器对象
    IoAcceptor acceptor = new NioSocketAcceptor();
    // 增加日志过滤器:用于日志存储
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    // 增加消息编码过滤器,采用UTF-8编码
    acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
    // 设置具体的事物逻辑处理器
    acceptor.setHandler(new TimeServerHandler());
    // 设置IoSession的一些属性
    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
    // 设置服务器监听的端口
    acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #10
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 #11
Source File: MinaTimeServer.java    From frameworkAggregate with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		IoAcceptor acceptor = new NioSocketAcceptor();
		// 这个过滤器用来记录所有的信息,比如创建session(会话),接收消息,发送消息,关闭会话等
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// 用来转换二进制或协议的专用数据到消息对象中
		acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

		// 实时处理客户端的连接和请求
		acceptor.setHandler(new TimeServerHandler());
		acceptor.getSessionConfig().setReadBufferSize(2048);
		// 方法将定时调用一次会话,保持空闲状态。来设定时间间隔。
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		acceptor.bind(new InetSocketAddress(PORT));
	}
 
Example #12
Source File: SlaveHost.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create a new slave host and bind to a single TCP port
 *
 * @param options
 *            optional protocol options
 * @param port
 *            the TCP port to bind to
 */
public SlaveHost ( final ProtocolOptions options, final int port ) throws IOException
{
    this.options = makeOptions ( options );

    this.connector = null;

    this.processor = new SimpleIoProcessorPool<> ( NioProcessor.class );
    final SocketAcceptor nioAcceptor = new NioSocketAcceptor ( this.processor );
    this.acceptor = nioAcceptor;

    nioAcceptor.setReuseAddress ( true );
    nioAcceptor.setBacklog ( 5 );

    this.disposeAcceptor = true;

    setupAcceptor ( null );

    this.acceptor.bind ( new InetSocketAddress ( port ) );
}
 
Example #13
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 #14
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 #15
Source File: MinaTimeServer.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	IoAcceptor acceptor = new NioSocketAcceptor();
	acceptor.getFilterChain().addLast("logger", new LoggingFilter());
	acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));// 指定编码过滤器
	acceptor.setHandler(new TimeServerHandler());// 指定业务逻辑处理器

	//读写 通道均在3 秒内无任何操作就进入空闲状态
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 3);

	acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT));// 设置端口号
	acceptor.bind();// 启动监听
}
 
Example #16
Source File: LoginServer.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public static void run_startup_configurations() {
    userLimit = ServerProperties.getProperty("userlimit", 140);
    serverName = ServerProperties.getProperty("serverName", "MapleStory");
    flag = ServerProperties.getProperty("flag", (byte) 3);
    adminOnly = Boolean.parseBoolean(ServerProperties.getProperty("admin", "false"));
    maxCharacters = ServerProperties.getProperty("maxCharacters", 30);
    autoReg = Boolean.parseBoolean(ServerProperties.getProperty("autoReg", "false"));
    checkMacs = Boolean.parseBoolean(ServerProperties.getProperty("checkMacs", "false"));
    port = Short.parseShort(ServerProperties.getProperty("world.port", String.valueOf(DEFAULT_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);

    try {
        acceptor.setHandler(new MapleServerHandler(MapleServerHandler.LOGIN_SERVER));
        acceptor.bind(new InetSocketAddress(port));
        ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);

        FileoutputUtil.log("\"登入\"伺服器正在监听" + port + "端口\r\n");
    } catch (IOException e) {
        System.err.println("无法绑定" + port + "端口: " + e);
    }
}
 
Example #17
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 #18
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 #19
Source File: HelloTcpServer.java    From mina-examples with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	IoAcceptor acceptor = new NioSocketAcceptor(); //TCP Acceptor
	acceptor.getFilterChain().addLast("logging", new LoggingFilter());
	acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
	acceptor.getFilterChain().addLast("mdc", new MdcInjectionFilter());
	acceptor.setHandler(new HelloServerHandler());
	acceptor.getSessionConfig().setReadBufferSize(2048);
	acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
	acceptor.bind(new InetSocketAddress(PORT));
}
 
Example #20
Source File: ConnectionListener.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the MINA-specific socket acceptor that is managed by the instance.
 *
 * @return A socket acceptor, or null when this listener is disabled or not based on a MINA implementation.
 */
// TODO see if we can avoid exposing MINA internals.
public NioSocketAcceptor getSocketAcceptor()
{
    if ( connectionAcceptor == null || !(connectionAcceptor instanceof MINAConnectionAcceptor) )
    {
        return null;
    }

    return ((MINAConnectionAcceptor)connectionAcceptor).getSocketAcceptor();
}
 
Example #21
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 #22
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 判断某个session是否在连接状态
 */
public final boolean hasSession(IoSession session)
{
	long sid = session.getId();
	NioSocketAcceptor acceptor = _acceptor;
	if (acceptor != null && acceptor.getManagedSessions().containsKey(sid))
		return true;
	NioSocketConnector connector = _connector;
	return connector != null && connector.getManagedSessions().containsKey(sid);
}
 
Example #23
Source File: MinaServer.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public void start(final int port,final ServerHandler handler) {

    this.serverDaemon = new Thread(new Runnable() {
        @Override
        public void run() {
            final MinaServerHandler serverHandler = new MinaServerHandler(handler);
            socketAddress = new InetSocketAddress(port);

            acceptor = new NioSocketAcceptor();
            acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecAdapter(Response.class, Request.class)));
            acceptor.setHandler(serverHandler);
            try {
                acceptor.bind(socketAddress);
                if (logger.isInfoEnabled()) {
                    logger.info("[JobX] MinaServer start at address:{} success", port);
                }
            } catch (IOException e) {
                logger.error("[JobX] MinaServer start failure: {}", stackTrace(e));
            }
        }
    });
    this.serverDaemon.setDaemon(true);
    this.serverDaemon.start();

    threadPoolExecutor = new ThreadPoolExecutor(50, 100, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
        private final AtomicInteger idGenerator = new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "MinaServer" + this.idGenerator.incrementAndGet());
        }
    });

}
 
Example #24
Source File: ServerBase.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public ServerBase ( final Collection<InetSocketAddress> addresses, final ProtocolConfigurationFactory protocolConfigurationFactory ) throws Exception
{
    this.addresses = addresses;

    this.acceptor = new NioSocketAcceptor ();
    this.acceptor.setReuseAddress ( true );

    this.chainBuilder = new FilterChainBuilder ( false );
    this.chainBuilder.setLoggerName ( ServerBase.class.getName () + ".protocol" );

    this.acceptor.setFilterChainBuilder ( this.chainBuilder );
    this.acceptor.setHandler ( new ServerBaseHandler ( this, protocolConfigurationFactory.createConfiguration ( false ) ) );
}
 
Example #25
Source File: SlaveHost.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a new slave host and bind to a list of socket addresses
 *
 * @param options
 *            optional protocol options
 * @param socketAddresses
 *            a list of socket addresses to bind to.
 *            <em>Note:<em> these socket addresses must be addresses of
 *            local interfaces, not remote addresses.
 */
public SlaveHost ( final ProtocolOptions options, final SlaveHostCustomizer slaveHostCustomizer, final SocketAddress... socketAddresses ) throws IOException
{
    this.options = makeOptions ( options );

    this.connector = null;

    this.processor = new SimpleIoProcessorPool<> ( NioProcessor.class );
    this.acceptor = new NioSocketAcceptor ( this.processor );
    this.disposeAcceptor = true;

    setupAcceptor ( slaveHostCustomizer );

    this.acceptor.bind ( socketAddresses );
}
 
Example #26
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 #27
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 #28
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 #29
Source File: MTGGameRoomServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public MTGGameRoomServer() throws IOException {

		super();
		acceptor = new NioSocketAcceptor();
		acceptor.setHandler(adapter);
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		acceptor.getSessionConfig().setReadBufferSize(getInt("BUFFER-SIZE"));
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,getInt("IDLE-TIME"));
	}
 
Example #30
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 停止服务器端的监听并断开相关的连接
 * @param addr 指定停止的地址/端口. 如果为null则停止全部监听地址/端口
 */
public void stopServer(InetSocketAddress addr)
{
	NioSocketAcceptor acceptor = getAcceptor();
	if (addr != null)
		acceptor.unbind(addr);
	else
		acceptor.unbind();
}