org.apache.mina.transport.socket.nio.NioSocketConnector Java Examples
The following examples show how to use
org.apache.mina.transport.socket.nio.NioSocketConnector.
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: MinaClient.java From grain with MIT License | 6 votes |
/** * 初始化 * * @param ipArray * ip地址数组 * @param portArray * 端口数组 * @param nameArray * 名称数组 * @throws Exception */ public MinaClient(String[] ipArray, int[] portArray, String[] nameArray, Class<?> HandlerClass) throws Exception { for (int i = 0; i < ipArray.length; i++) { String ip = ipArray[i]; int port = portArray[i]; String name = nameArray[i]; IoConnector ioConnector = new NioSocketConnector(); ioConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder())); MinaHandler minaHandler = (MinaHandler) HandlerClass.newInstance(); minaHandler.ioConnector = ioConnector; minaHandler.name = name; ioConnector.setHandler(minaHandler); ioConnector.setConnectTimeoutMillis(10000); InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port); ioConnectorMap.put(ioConnector, inetSocketAddress); ioConnectorStateMap.put(ioConnector, false); } start(); }
Example #2
Source File: ModbusMaster.java From neoscada with Eclipse Public License 1.0 | 6 votes |
@Override protected void configureConnector ( final NioSocketConnector connector ) { logger.debug ( "Configuring connector: {}", connector ); switch ( this.protocolType ) { case TYPE_TCP: connector.getFilterChain ().addLast ( "modbusPdu", new ProtocolCodecFilter ( new ModbusTcpEncoder (), new ModbusTcpDecoder () ) ); connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () ); break; case TYPE_RTU: // convert milliseconds to microseconds to allow more accurate timing final ModbusRtuDecoder rtuDecoder = new ModbusRtuDecoder ( getExecutor (), Double.valueOf ( this.interFrameDelay * 1000 ).longValue (), TimeUnit.MICROSECONDS ); connector.getFilterChain ().addLast ( "modbusPdu", new ModbusRtuProtocolCodecFilter ( new ModbusRtuEncoder (), rtuDecoder ) ); connector.getFilterChain ().addLast ( "modbus", new ModbusMasterProtocolFilter () ); break; default: throw new IllegalArgumentException ( String.format ( "'%s' is not an allowed modbus device type", this.protocolType ) ); } if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.osgi.modbus.trace" ) ) { connector.getFilterChain ().addFirst ( "logger", new LoggingFilter ( ModbusMaster.class.getName () + ".protocol" ) ); } }
Example #3
Source File: MinaRemotingClient.java From light-task-scheduler with Apache License 2.0 | 6 votes |
@Override protected void clientStart() throws RemotingException { try { connector = new NioSocketConnector(); //TCP Connector // connector.getFilterChain().addFirst("logging", new MinaLoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecFactory(getCodec()))); connector.getFilterChain().addLast("mdc", new MdcInjectionFilter()); connector.setHandler(new MinaHandler(this)); IoSessionConfig cfg = connector.getSessionConfig(); cfg.setReaderIdleTime(remotingClientConfig.getReaderIdleTimeSeconds()); cfg.setWriterIdleTime(remotingClientConfig.getWriterIdleTimeSeconds()); cfg.setBothIdleTime(remotingClientConfig.getClientChannelMaxIdleTimeSeconds()); } catch (Exception e) { throw new RemotingException("Mina Client start error", e); } }
Example #4
Source File: HelloTcpClient.java From mina-examples with MIT License | 6 votes |
public static void main(String[] args) { NioSocketConnector connector = new NioSocketConnector(); //TCP Connector connector.getFilterChain().addLast("logging", new LoggingFilter()); connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.getFilterChain().addLast("mdc", new MdcInjectionFilter()); connector.setHandler(new HelloClientHandler()); IoSession session; for (;;) { try { ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT)); future.awaitUninterruptibly(); session = future.getSession(); break; } catch (RuntimeIoException e) { System.err.println("Failed to connect."); e.printStackTrace(); } } session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); }
Example #5
Source File: SocketConnectorSupplier.java From sumk with Apache License 2.0 | 6 votes |
private synchronized SocketConnector create() { if (connector != null && !connector.isDisposing() && !connector.isDisposed()) { return connector; } try { NioSocketConnector con = new NioSocketConnector( AppInfo.getInt("sumk.rpc.client.poolsize", Runtime.getRuntime().availableProcessors() + 1)); con.setConnectTimeoutMillis(AppInfo.getInt("sumk.rpc.connect.timeout", 5000)); con.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, AppInfo.getInt(Const.SOA_SESSION_IDLE, 600)); con.setHandler(createClientHandler()); con.getFilterChain().addLast("codec", new ProtocolCodecFilter(IOC.get(SumkCodecFactory.class))); if (AppInfo.getBoolean("sumk.rpc.client.threadpool.enable", true)) { con.getFilterChain().addLast("threadpool", new ExecutorFilter(SoaExcutors.getClientThreadPool())); } this.connector = con; return con; } catch (Exception e) { Logs.rpc().error(e.getMessage(), e); throw new SumkException(5423654, "create connector error", e); } }
Example #6
Source File: MinaClient.java From java-study with Apache License 2.0 | 6 votes |
public static void main(String[] args) { // 创建一个非阻塞的客户端程序 IoConnector connector = new NioSocketConnector(); // 设置链接超时时间 connector.setConnectTimeout(30000); ProtocolCodecFilter pf=new ProtocolCodecFilter((new MyTextLineCodecFactory(Charset .forName("utf-8"), "\r\n"))); // 添加过滤器 connector.getFilterChain().addLast("codec", pf); // 添加业务逻辑处理器类 connector.setHandler(new MinaClientHandler()); IoSession session = null; try { ConnectFuture future = connector.connect(new InetSocketAddress( HOST, PORT));// 创建连接 future.awaitUninterruptibly();// 等待连接创建完成 session = future.getSession();// 获得session String msg="hello \r\n"; session.write(msg);// 发送消息 logger.info("客户端与服务端建立连接成功...发送的消息为:"+msg); } catch (Exception e) { e.printStackTrace(); logger.error("客户端链接异常...", e); } session.getCloseFuture().awaitUninterruptibly();// 等待连接断开 connector.dispose(); }
Example #7
Source File: MinaTcpClient.java From game-server with MIT License | 6 votes |
/** * 初始化tcp连接 * @param clientProtocolHandler */ private void init(IoHandler clientProtocolHandler) { connector = new NioSocketConnector(); DefaultIoFilterChainBuilder chain = connector.getFilterChain(); chain.addLast("codec", codecFilter); if(filters != null){ filters.forEach((key, filter)->{ if("ssl".equalsIgnoreCase(key) || "tls".equalsIgnoreCase(key)){ //ssl过滤器必须添加到首部 chain.addFirst(key, filter); }else{ chain.addLast(key, filter); } }); } connector.setHandler(clientProtocolHandler); connector.setConnectTimeoutMillis(60000L); connector.setConnectTimeoutCheckInterval(10000); }
Example #8
Source File: Main.java From TestClient with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { //网络链接工具 NetSupport support = new NetSupport(); //创建回话链 ConversationChain chain = new ConversationChain(support); buildConversation(chain); //设置会话链 support.setConversationChain(chain); NioSocketConnector connector = new NioSocketConnector(); SocketAddress address = new InetSocketAddress("localhost", 1101); boolean isConnected = support.connect(connector, address); if(isConnected){ support.startConversation(); } support.quit(); connector.dispose(); }
Example #9
Source File: Robot.java From jforgame with Apache License 2.0 | 6 votes |
public void doConnection() { NioSocketConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory())); connector.setHandler(new ClientHandler()); System.out.println("开始连接socket服务端"); int serverPort = ServerConfig.getInstance().getServerPort(); ConnectFuture future = connector.connect(new InetSocketAddress(serverPort)); future.awaitUninterruptibly(); IoSession session = future.getSession(); this.session = new RobotSession(this, session); this.session.registerMessageHandler(); this.login(); }
Example #10
Source File: WebSocketServerTest.java From red5-websocket with Apache License 2.0 | 5 votes |
public WSClient(String host, int port) { this.host = host; this.port = port; connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebSocketCodecFactory())); connector.setHandler(this); SocketSessionConfig sessionConf = connector.getSessionConfig(); sessionConf.setReuseAddress(true); connector.setConnectTimeout(3); }
Example #11
Source File: MinaTimeClient.java From javabase with Apache License 2.0 | 5 votes |
public static void main(String[] args) { // 创建客户端连接器. NioSocketConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器 connector.setConnectTimeout(30); connector.setHandler(new TimeClientHandler());// 设置事件处理器 ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9123));// 建立连接 cf.awaitUninterruptibly();// 等待连接创建完成 cf.getSession().write("hello");// 发送消息 cf.getSession().write("quit");// 发送消息 cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开 connector.dispose(); }
Example #12
Source File: AbstractTcpClient.java From util with Apache License 2.0 | 5 votes |
/** * Create the UdpClient's instance */ public AbstractTcpClient() { connector = new NioSocketConnector(); connector.setHandler(this); ConnectFuture connFuture = connector.connect(new InetSocketAddress(getServerIp(), getServerPort())); connFuture.awaitUninterruptibly(); session = connFuture.getSession(); }
Example #13
Source File: DefaultRedisConnection.java From Redis-Synyed with Apache License 2.0 | 5 votes |
/** * 执行连接操作的方法 * * @throws RedisProtocolException * 当连接出现问题时抛出该异常 */ private void connect() throws RedisProtocolException { connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(connectionTimeOut); connector.getFilterChain().addFirst("redis-protocol", new ProtocolCodecFilter(new RedisProtocolCodecFactory())); connector.setHandler(this); connector.connect(new InetSocketAddress(address, port)); }
Example #14
Source File: MinaClient.java From MtgDesktopCompanion with GNU General Public License v3.0 | 5 votes |
public MinaClient(String server, int port) { p = new Player(); connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.setHandler(adapter); ConnectFuture connFuture = connector.connect(new InetSocketAddress(server, port)); connFuture.awaitUninterruptibly(); session = connFuture.getSession(); }
Example #15
Source File: NetSupport.java From TestClient with Apache License 2.0 | 5 votes |
public boolean connect(NioSocketConnector connector, SocketAddress address) { if(!isSetChain){ throw new IllegalStateException( "please set ConservationChain first !"); } if (session != null && session.isConnected()) { throw new IllegalStateException( "Already connected. Disconnect first."); } try { IoFilter CODEC_FILTER = new ProtocolCodecFilter( new GameProtocolcodecFactory()); connector.getFilterChain().addLast("codec", CODEC_FILTER); connector.setHandler(handler); ConnectFuture future1 = connector.connect(address); future1.awaitUninterruptibly(); if (!future1.isConnected()) { return false; } session = future1.getSession(); return true; } catch (Exception e) { return false; } }
Example #16
Source File: StreamBaseDevice.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override public synchronized void connect () { if ( isConnected () ) { logger.info ( "Already connected" ); return; } if ( this.connector == null ) { this.connector = new NioSocketConnector (); this.connector.setHandler ( this ); if ( Boolean.getBoolean ( "org.eclipse.scada.da.server.io.common.trace" ) ) { this.connector.getFilterChain ().addLast ( "logger", new LoggingFilter () ); } setupConnector ( this.connector ); } final ConnectFuture cu = this.connector.connect ( this.address ); cu.addListener ( new IoFutureListener<ConnectFuture> () { @Override public void operationComplete ( final ConnectFuture future ) { try { future.getSession (); } catch ( final Throwable e ) { StreamBaseDevice.this.fireConnectionFailed ( e ); } } } ); }
Example #17
Source File: WebSocketServerTest.java From red5-websocket with Apache License 2.0 | 5 votes |
public WSClient(String host, int port, int cookieLength) { this.cookie = RandomStringUtils.randomAscii(cookieLength); log.debug("Cookie length: {}", cookie.length()); this.host = host; this.port = port; connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebSocketCodecFactory())); connector.setHandler(this); SocketSessionConfig sessionConf = connector.getSessionConfig(); sessionConf.setReuseAddress(true); connector.setConnectTimeout(3); }
Example #18
Source File: GameClient.java From gameserver with Apache License 2.0 | 5 votes |
/** * Connect to remote message server. * @return */ public boolean connectToServer() { try { resourceLock.lock(); if ( log.isInfoEnabled() ) { log.info("Connect to message server : " + remoteHost + ":" + remotePort); } connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new GameProtocolCodecFilter()); connector.setHandler(this.handler); int heartBeatSecond = GlobalConfig.getInstance().getIntProperty("message.heartbeat.second"); if ( log.isDebugEnabled() ) { log.debug("heartBeatSecond : " + heartBeatSecond); } connector.getSessionConfig().setBothIdleTime(heartBeatSecond); // Make a new connection ConnectFuture connectFuture = connector.connect(new InetSocketAddress(remoteHost, remotePort)); // Wait until the connection is make successfully. connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT); try { session = connectFuture.getSession(); //Tell caller we can write message. // connectedCond.signal(); if ( log.isInfoEnabled() ) { log.info("connect to " + remoteHost + ":" + remotePort); } return true; } catch (Throwable e) { disconnectFromServer(); return false; } } finally { resourceLock.unlock(); } }
Example #19
Source File: Client.java From gameserver with Apache License 2.0 | 5 votes |
public Client(ArrayList<Class> testCases, String host, int port, boolean longRunning) throws Exception { // Set up this.longRunning = longRunning; this.testcaseClasses = testCases; this.testcases = new ArrayList(this.testcaseClasses.size()); for ( int i=0; i<this.testcaseClasses.size(); i++ ) { this.testcases.add(this.testcaseClasses.get(i).newInstance()); logger.info("testcase: " + this.testcaseClasses.get(i)); } this.context = new EnumMap<ContextKey, Object>(ContextKey.class); connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ProtobufEncoder(), new ProtobufDecoder())); connector.setHandler(this); // Make a new connection ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port)); // Wait until the connection is make successfully. connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT); try { session = connectFuture.getSession(); logger.info("client connected"); } catch (RuntimeIoException e) { e.printStackTrace(); if ( session != null ) { session.close(); } } }
Example #20
Source File: TestReloadClassLoader.java From gameserver with Apache License 2.0 | 5 votes |
@Test public void testClassLoaderLeak2() throws Exception { int max = 10000; File sourceFile = new File(reloadSourceDir); URL[] urls = new URL[]{sourceFile.toURL()}; // ReloadProtocolCodecFilter filter = ReloadProtocolCodecFilter.getInstance( // GameServer.PROTOCOL_CODEC, GameServer.PROTOCOL_HANDLER, urls); SocketConnector connector = new NioSocketConnector(); // connector.getFilterChain().addLast("codec", filter); connector.setHandler(new ClientHandler()); //Send 1000 connections. try { for ( int i=0; i<Integer.MAX_VALUE; i++ ) { ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 3443)); future.awaitUninterruptibly(); IoSession session = future.getSession(); IoBuffer buffer = IoBuffer.allocate(8); buffer.putShort((short)8); buffer.putShort((short)0); buffer.putInt(i); WriteFuture wfuture = session.write(buffer); wfuture.awaitUninterruptibly(); } } catch (Exception e) { e.printStackTrace(); fail(); } }
Example #21
Source File: NetManager.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
/** * 判断某个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 #22
Source File: NetManager.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
/** * 停止全部相关客户端的连接 * @param force 是否立即强制关闭(丢弃当前的发送缓存) */ public void stopAllClients(boolean force) { NioSocketConnector connector = _connector; if (connector != null) { for (IoSession session : connector.getManagedSessions().values()) { if (force) session.closeNow(); else closeOnFlush(session); } } }
Example #23
Source File: DaveDevice.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override protected void configureConnector ( final NioSocketConnector connector ) { connector.getFilterChain ().addLast ( "tpkt", new TPKTFilter ( 3 ) ); connector.getFilterChain ().addLast ( "cotp", new COTPFilter ( this.rack, this.slot ) ); connector.getFilterChain ().addLast ( "dave", new DaveFilter () ); }
Example #24
Source File: ClientBaseConnection.java From neoscada with Eclipse Public License 1.0 | 5 votes |
protected ClientBaseConnection ( final IoHandlerFactory handlerFactory, final IoLoggerFilterChainBuilder chainBuilder, final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception { super ( connectionInformation ); this.stateNotifier = new StateNotifier ( this.executor, this ); this.handler = handlerFactory.create ( this ); if ( processor != null ) { this.connector = new NioSocketConnector ( processor ); } else { this.connector = new NioSocketConnector (); } this.chainBuilder = chainBuilder; this.chainBuilder.setLoggerName ( ClientBaseConnection.class.getName () + ".protocol" ); this.connector.setFilterChainBuilder ( this.chainBuilder ); this.connector.setHandler ( this.handler ); this.statistics.setLabel ( STATS_CACHE_ADDRESS, "Flag if the IP address gets cached" ); this.statistics.setCurrentValue ( STATS_CACHE_ADDRESS, this.cacheAddress ? 1.0 : 0.0 ); this.statistics.setLabel ( STATS_CURRENT_STATE, "Numeric connection state" ); this.statistics.setLabel ( STATS_CONNECT_CALLS, "Calls to connect" ); this.statistics.setLabel ( STATS_DISCONNECT_CALLS, "Calls to disconnect" ); this.statistics.setLabel ( STATS_MESSAGES_SENT, "Messages sent" ); this.statistics.setLabel ( STATS_MESSAGES_RECEIVED, "Messages received" ); this.statistics.setLabel ( STATS_CREATION_TIMESTAMP, "Timestamp of creation (in seconds)" ); this.statistics.setCurrentValue ( STATS_CREATION_TIMESTAMP, Math.floor ( System.currentTimeMillis () / 1000 ) ); this.statistics.setLabel ( STATS_LAST_CONNECT_TIMESTAMP, "Timestamp of last CONNECT (in seconds)" ); this.statistics.setLabel ( STATS_LAST_BOUND_TIMESTAMP, "Timestamp of last BOUND (in seconds)" ); }
Example #25
Source File: Application1.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override public Object start ( final IApplicationContext context ) throws Exception { final NioSocketConnector connector = new NioSocketConnector (); connector.setHandler ( new SingleSessionIoHandlerDelegate ( new SingleSessionIoHandlerFactory () { @Override public SingleSessionIoHandler getHandler ( final IoSession session ) throws Exception { return new DaveHandler ( session ); } } ) ); connector.getFilterChain ().addLast ( "logger", new LoggingFilter ( this.getClass ().getName () ) ); connector.getFilterChain ().addLast ( "tpkt", new TPKTFilter ( 3 ) ); connector.getFilterChain ().addLast ( "cotp", new COTPFilter ( 0, (byte)3 ) ); connector.getFilterChain ().addLast ( "dave", new DaveFilter () ); connector.connect ( new InetSocketAddress ( "192.168.1.83", 102 ) ); while ( this.running ) { Thread.sleep ( 1000 ); } return null; }
Example #26
Source File: MimaTimeClient.java From frameworkAggregate with Apache License 2.0 | 5 votes |
public static void main(String[] args) { IoConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(new TimeClientHander()); ConnectFuture connectFuture = connector.connect(new InetSocketAddress("127.0.0.1", PORT)); // 等待建立连接 connectFuture.awaitUninterruptibly(); System.out.println("连接成功"); IoSession session = connectFuture.getSession(); Scanner sc = new Scanner(System.in); boolean quit = false; while (!quit) { String str = sc.next(); if (str.equalsIgnoreCase("quit")) { quit = true; } session.write(str); } // 关闭 if (session != null) { if (session.isConnected()) { session.getCloseFuture().awaitUninterruptibly(); } connector.dispose(true); } }
Example #27
Source File: MinaUtil.java From seed with Apache License 2.0 | 5 votes |
/** * 发送TCP消息 * <p> * 当通信发生异常时(Fail to get session...),返回“MINA_SERVER_ERROR”字符串 * </p> * @param message 待发送报文的中文字符串形式 * @param ipAddress 远程主机的IP地址 * @param port 远程主机的端口号 * @param charset 该方法与远程主机间通信报文为编码字符集(编码为byte[]发送到Server) * @return 远程主机响应报文的字符串形式 */ public static String sendTCPMessage(String message, String ipAddress, int port, String charset){ IoConnector connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(DEFAULT_CONNECTION_TIMEOUT); //同步的客户端,必须设置此项,其默认为false connector.getSessionConfig().setUseReadOperation(true); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ClientProtocolEncoder(charset), new ClientProtocolDecode(charset))); //作为同步的客户端,可以不需要IoHandler,Mina会自动添加一个默认的IoHandler实现(即AbstractIoConnector) //connector.setHandler(this); IoSession session = null; Object respData = null; try{ ConnectFuture connectFuture = connector.connect(new InetSocketAddress(ipAddress, port)); connectFuture.awaitUninterruptibly(); //等待连接成功,相当于将异步执行转为同步执行 session = connectFuture.getSession(); //获取连接成功后的会话对象 session.write(message).awaitUninterruptibly(); //由于上面已经设置setUseReadOperation(true),故IoSession.read()方法才可用 ReadFuture readFuture = session.read(); //因其内部使用BlockingQueue,故Server端用之可能会内存泄漏,但Client端可适当用之 //Wait until the message is received if(readFuture.awaitUninterruptibly(DEFAULT_BOTHIDLE_TIMEOUT, TimeUnit.SECONDS)){ //Get the received message respData = readFuture.getMessage(); }else{ LogUtil.getLogger().warn("读取[/" + ipAddress + ":" + port + "]超时"); } }catch(Exception e){ LogUtil.getLogger().error("请求通信[/" + ipAddress + ":" + port + "]偶遇异常,堆栈轨迹如下", e); }finally{ if(session != null){ //关闭IoSession,该操作是异步的,true为立即关闭,false为所有写操作都flush后关闭 //这里仅仅是关闭了TCP的连接通道,并未关闭Client端程序 //session.close(true); session.closeNow(); //客户端发起连接时,会请求系统分配相关的文件句柄,而在连接失败时记得释放资源,否则会造成文件句柄泄露 //当总的文件句柄数超过系统设置值时[ulimit -n],则抛异常"java.io.IOException: Too many open files",导致新连接无法创建,服务器挂掉 //所以:若不关闭的话,其运行一段时间后可能抛出too many open files异常,导致无法连接 session.getService().dispose(); } } return respData==null ? "MINA_SERVER_ERROR" : respData.toString(); }
Example #28
Source File: LdapNetworkConnection.java From directory-ldap-api with Apache License 2.0 | 5 votes |
/** * Create the connector * * @throws LdapException If the connector can't be created */ private void createConnector() throws LdapException { // Use only one thread inside the connector connector = new NioSocketConnector( 1 ); if ( socketSessionConfig != null ) { ( ( SocketSessionConfig ) connector.getSessionConfig() ).setAll( socketSessionConfig ); } else { ( ( SocketSessionConfig ) connector.getSessionConfig() ).setReuseAddress( true ); } // Add the codec to the chain connector.getFilterChain().addLast( "ldapCodec", ldapProtocolFilter ); // If we use SSL, we have to add the SslFilter to the chain if ( config.isUseSsl() ) { addSslFilter(); } // Inject the protocolHandler connector.setHandler( this ); }
Example #29
Source File: ClientPlayer.java From jforgame with Apache License 2.0 | 5 votes |
public void buildConnection() { NioSocketConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory())); connector.setHandler(new ClientHandler()); int serverPort = ServerConfig.getInstance().getServerPort(); System.out.println("开始连接游戏服务器端口" + serverPort); ConnectFuture future = connector.connect(new InetSocketAddress(serverPort)); future.awaitUninterruptibly(); IoSession session = future.getSession(); this.session = session; }
Example #30
Source File: ConnectorTest.java From game-server with MIT License | 5 votes |
@Test public void testTCPWithSSL() throws Exception { useSSL = true; // Create a connector IoConnector connector = new NioSocketConnector(); // Add an SSL filter to connector connector.getFilterChain().addLast("SSL", connectorSSLFilter); testConnector(connector); }