org.apache.mina.core.service.IoConnector Java Examples
The following examples show how to use
org.apache.mina.core.service.IoConnector.
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 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 #2
Source File: ClientSideIoHandler.java From sailfish-core with Apache License 2.0 | 6 votes |
public ClientSideIoHandler(IoConnector connector, SocketAddress remoteAddress, IMessageStorage storage, IServiceHandler handler, TCPIPProxy proxyService, ILoggingConfigurator logConfigurator, IDictionaryStructure dictionary, IMessageFactory factory, DirtyQFJIMessageConverter converter, ServiceName serviceName) { this.connector = connector; this.remoteAddress = remoteAddress; this.storage = storage; this.handler = handler; this.proxyService = proxyService; this.logConfigurator = logConfigurator; this.appDictionary = new QFJDictionaryAdapter(dictionary); this.converter = converter; this.serviceName = serviceName; connectorHandler = new ServerSideIoHandler(connector, storage, handler, proxyService, this.factory, appDictionary, converter); connectorHandler.setServiceInfo(serviceInfo); connector.setHandler(connectorHandler); }
Example #3
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 #4
Source File: ClientTestServer.java From java-study with Apache License 2.0 | 5 votes |
public IoConnector creatClient(){ IoConnector connector=new NioSocketConnector(); connector.setConnectTimeoutMillis(30000); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.setHandler(new MinaClientHandler()); return connector; }
Example #5
Source File: ClientTestServer.java From java-study with Apache License 2.0 | 5 votes |
public IoSession getIOSession(IoConnector connector){ ConnectFuture future = connector.connect(new InetSocketAddress("192.168.2.55", 1255)); // 等待是否连接成功,相当于是转异步执行为同步执行。 future.awaitUninterruptibly(); // 连接成功后获取会话对象。 如果没有上面的等待, 由于connect()方法是异步的, session可能会无法获取。 IoSession session = null; try{ session = future.getSession(); }catch(Exception e){ e.printStackTrace(); } return session; }
Example #6
Source File: ClientTestServer.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] args) { for(int i=0;i<4000;i++){ ClientTestServer client = new ClientTestServer(); IoConnector connector = client.creatClient(); IoSession session = client.getIOSession(connector); client.sendMsg(session,Arrays.toString(new byte[1000])+":"+System.currentTimeMillis()); } }
Example #7
Source File: ServerSideIoHandler.java From sailfish-core with Apache License 2.0 | 5 votes |
public ServerSideIoHandler(IoConnector connector, IMessageStorage storage, IServiceHandler handler, TCPIPProxy proxyService, DefaultMessageFactory factory, DataDictionary appDictionary, DirtyQFJIMessageConverter converter) { this.storage = storage; this.handler = handler; this.proxyService = proxyService; this.factory = factory; this.appDictionary = appDictionary; this.converter = converter; }
Example #8
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); }
Example #9
Source File: MinaClient.java From grain with MIT License | 5 votes |
/** * 守护,启动链接、断线重连 */ @Override public void run() { while (true) { Set<IoConnector> keySet = ioConnectorMap.keySet(); Iterator<IoConnector> iterator = keySet.iterator(); for (int i = 0; i < keySet.size(); i++) { IoConnector ioConnector = iterator.next(); InetSocketAddress inetSocketAddress = ioConnectorMap.get(ioConnector); boolean isConnected = ioConnectorStateMap.get(ioConnector); if (!isConnected) { ConnectFuture connectFuture = ioConnector.connect(inetSocketAddress); connectFuture.awaitUninterruptibly(); if (!connectFuture.isConnected()) { connectFuture.cancel(); if (MinaConfig.log != null) { MinaConfig.log.info("连接" + inetSocketAddress.toString() + "失败"); } } else { ioConnectorStateMap.put(ioConnector, true); if (MinaConfig.log != null) { MinaConfig.log.info("连接" + inetSocketAddress.toString() + "成功"); } } } } try { Thread.sleep(MinaClient.MINA_CLIENT_RECONNECT_INTERVAL); } catch (InterruptedException e) { if (MinaConfig.log != null) { MinaConfig.log.error("守护线程minaclient异常", e); } } } }
Example #10
Source File: ConnectorTest.java From game-server with MIT License | 5 votes |
private void testConnector(IoConnector connector) throws Exception { connector.setHandler(handler); //System.out.println("* Without localAddress"); testConnector(connector, false); //System.out.println("* With localAddress"); testConnector(connector, true); }
Example #11
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 #12
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 #13
Source File: SlaveHost.java From neoscada with Eclipse Public License 1.0 | 5 votes |
public SlaveHost ( final ProtocolOptions options, final IoConnector connector, final SlaveHostCustomizer slaveHostCustomizer ) { this.options = makeOptions ( options ); this.connector = connector; this.acceptor = null; this.processor = null; this.disposeAcceptor = false; setupConnector ( slaveHostCustomizer ); }
Example #14
Source File: ConnectorTest.java From game-server with MIT License | 4 votes |
@Test public void testUDP() throws Exception { IoConnector connector = new NioDatagramConnector(); testConnector(connector); }
Example #15
Source File: MyClient.java From jlogstash-input-plugin with Apache License 2.0 | 4 votes |
public static void main(String[] args) { // 创建一个非组设的客户端客户端 IoConnector connector = new NioSocketConnector(); // 设置链接超时时间 connector.setConnectTimeoutMillis(30000); // 添加过滤器 connector.getFilterChain().addLast( // 添加消息过滤器 "codec", // Mina自带的根据文本换行符编解码的TextLineCodec过滤器 看到\r\n就认为一个完整的消息结束了 new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8"), LineDelimiter.MAC.getValue(), LineDelimiter.MAC.getValue()))); // 添加业务逻辑处理器类 connector.setHandler(new ClientMessageHandler()); IoSession session = null; try { ConnectFuture future = connector.connect(new InetSocketAddress( HOST, PORT)); future.awaitUninterruptibly(); // 等待连接创建完成 session = future.getSession(); long t1 = System.currentTimeMillis(); StringBuffer sb = new StringBuffer(); for(int i=0;i<200000;i++){ System.out.println(i); sb.append("ysqysq nginx_ccc [0050d2bf234311e6ba8cac853da49b78 type=nginx_access_log tag=\"mylog\"] /Users/sishuyss/ysq_access/$2016-04-05T11:12:24.230148+08:00/$100.97.184.152 - - [25/May/2016:01:10:07 +0800] \"GET /index.php?disp=dynamic HTTP/1.0\" 301 278 \"http://log.dtstack.com/\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;Alibaba.Security.Heimdall.1142964)\" 121.42.0.85 - - - 0").append(LineDelimiter.UNIX.getValue()); if(i%200==0){ session.write(sb.toString()); sb = new StringBuffer(); } } session.write(sb.toString()); System.out.println("time:"+(System.currentTimeMillis()-t1)); } catch (Exception e) { System.out.println(e.getCause()); logger.info("客户端链接异常..."); } session.getCloseFuture().awaitUninterruptibly(); logger.info("Mina要关闭了"); connector.dispose(); }
Example #16
Source File: CalculatorClient.java From mina with Apache License 2.0 | 4 votes |
@Override public void run() { IoConnector connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);//设置连接超时时间(毫秒数) connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CommandCodecFactory("UTF-8"))); KeepAliveMessageFactoryImpl kamfi = new KeepAliveMessageFactoryImpl(); KeepAliveFilter kaf = new KeepAliveFilter(kamfi, IdleStatus.READER_IDLE, KeepAliveRequestTimeoutHandler.CLOSE); /** 是否回发 */ kaf.setForwardEvent(true); connector.getFilterChain().addLast("heart", kaf); connector.setHandler(new CalculatorClientHander()); ConnectFuture connectFuture = connector.connect(new InetSocketAddress(IP, PORT)); //等待建立连接 connectFuture.awaitUninterruptibly(); if(!connectFuture.isConnected()){ log.debug("连接失败"); return ; } log.debug("连接成功"); IoSession session = connectFuture.getSession(); // try { // Cmd1003 cmd1003 = (Cmd1003) CommandFactory.createCommand(CidConst.C1003); // cmd1003.getReqMsg().setCpu(0.3f); // cmd1003.getReqMsg().setDisk(0.24f); // cmd1003.getReqMsg().setMemory(0.41f); // session.write(cmd1003); // } catch (Exception e) { // e.printStackTrace(); // } //关闭 if (session != null) { if (session.isConnected()) { session.getCloseFuture().awaitUninterruptibly(); } connector.dispose(true); } }
Example #17
Source File: MinaClient.java From java-study with Apache License 2.0 | 4 votes |
public static IoConnector getConnector() { return connector; }
Example #18
Source File: ConnectorTest.java From game-server with MIT License | 4 votes |
@Test public void testTCP() throws Exception { IoConnector connector = new NioSocketConnector(); testConnector(connector); }
Example #19
Source File: MinaClient.java From java-study with Apache License 2.0 | 4 votes |
public static void setConnector(IoConnector connector) { MinaClient.connector = connector; }
Example #20
Source File: LdapNetworkConnection.java From directory-ldap-api with Apache License 2.0 | 2 votes |
/** * Set the connector to use. * * @param connector The connector to use */ public void setConnector( IoConnector connector ) { this.connector = connector; }