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)); }
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)); }
public static void main(String[] args) { int port = U.getInt("cleaner.server.port"); int idleTime = U.getInt("cleaner.server.time"); NioSocketAcceptor clientAcceptor = new NioSocketAcceptor(); clientAcceptor.setReuseAddress(true); DefaultIoFilterChainBuilder chain = clientAcceptor.getFilterChain(); SocketSessionConfig config = clientAcceptor.getSessionConfig(); config.setIdleTime(IdleStatus.READER_IDLE, idleTime);// 读空闲 10秒 config.setReuseAddress(true); config.setReadBufferSize(4096);// 默认2048 config.setKeepAlive(true); config.setTcpNoDelay(true);// 开启nagle算法 // 编解码 chain.addLast("coder", new ProtocolCodecFilter(new TextLineCodecFactory(U.UTF8))); clientAcceptor.setHandler(new CleanerHandler()); try { clientAcceptor.bind(new InetSocketAddress(port)); log.info("心跳模块启动.."); } catch (IOException e) { log.error("心跳模块启动失败", e); } }
/** */ @PostConstruct public void start() throws IOException { if (this.acceptor != null) throw new IllegalStateException("TcpTableService already running"); InetAddress binding = null; String bindAddress = System.getProperty("jboss.bind.address"); if (bindAddress != null && !"0.0.0.0".equals(bindAddress)) binding = InetAddress.getByName(bindAddress); log.log(Level.INFO,"Starting TcpTableService: {0}:{1}", new Object[]{(binding==null ? "*" : binding),port}); this.acceptor = new SocketAcceptor(); this.acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory(Charset.forName("UTF-8")))); this.acceptor.bind(new InetSocketAddress(binding, this.port), new Handler()); }
public NIOSocketServerController(SocketServerConfig config) { this.setConfig(config); this.acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); acceptor.setHandler(this); acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); json = new JSON(); this.processorManager = new ProcessorManager(); }
private void initService() throws Exception { IoBuffer.setUseDirectBuffer(false); acceptor = new NioSocketAcceptor( Runtime.getRuntime().availableProcessors() + 1); config = acceptor.getSessionConfig(); config.setReuseAddress(true); DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); chain.addLast("codec", new ProtocolCodecFilter( new TextLineCodecFactory( MailsterConstants.DEFAULT_CHARSET, LineDelimiter.CRLF, LineDelimiter.CRLF))); executor = Executors.newCachedThreadPool( ThreadFactoryUtilities.createFactory("POP3 Thread")); chain.addLast("threadPool", new ExecutorFilter(executor)); handler = new Pop3ProtocolHandler(userManager); }
public MinaCubeClient(String hostname, int port) { this.hostname = hostname; this.port = port; connector = new NioSocketConnector(1); connector.setConnectTimeoutMillis(2000); connector.getFilterChain().addLast("logger", new LoggingFilter()); TextLineCodecFactory codecFactory = new TextLineCodecFactory(UTF_8, LineDelimiter.CRLF, LineDelimiter.AUTO); codecFactory.setDecoderMaxLineLength(4096); codecFactory.setEncoderMaxLineLength(4096); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory)); handler = new ConnectHandler(); connector.setHandler(handler); }
public void start() throws IOException { // enable for debug acceptor.getFilterChain().addLast("logger", new LoggingFilter()); TextLineCodecFactory codecFactory = new TextLineCodecFactory(UTF_8, LineDelimiter.CRLF, LineDelimiter.CRLF); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory)); acceptor.setHandler(handler); acceptor.bind(new InetSocketAddress(0) ); acceptor.setCloseOnDeactivation(true); logger.info("Cube server bound to [{}]", acceptor.getLocalAddress()); }
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(); }
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();// 启动监听 }
@Override public void emit() { // TODO Auto-generated method stub try { // ssl 认证 if (sslEnable) { SslFilter sslFilter = new SslFilter(getSslContext()); acceptor.getFilterChain().addLast("sslFilter", sslFilter); logger.warn("ssl authenticate is open"); } LoggingFilter loggingFilter = new LoggingFilter(); acceptor.getFilterChain().addLast("logger", loggingFilter); TextLineCodecFactory textLineCodecFactory = new TextLineCodecFactory( Charset.forName(encodiing)); textLineCodecFactory.setDecoderMaxLineLength(maxLineLength); textLineCodecFactory.setEncoderMaxLineLength(maxLineLength); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(textLineCodecFactory)); acceptor.setHandler(minaBizHandler); acceptor.getSessionConfig().setReadBufferSize(bufSize); acceptor.getSessionConfig().setWriteTimeout(10); // acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, // 10);//空闲状态 acceptor.bind(new InetSocketAddress(InetAddress.getByName(host), port)); } catch (Exception e) { // TODO Auto-generated catch block logger.error(e.getMessage()); System.exit(1); } }
@NonNull static TextLineCodecFactory getTextLineCodecFactory() { TextLineCodecFactory codec = new TextLineCodecFactory(); codec.setDecoderMaxLineLength(MAX_LINE_LENGTH); codec.setEncoderMaxLineLength(MAX_LINE_LENGTH); return codec; }
public void start() throws Exception { acceptor = new SocketAcceptor(); // Prepare the configuration SocketAcceptorConfig cfg = new SocketAcceptorConfig(); cfg.setReuseAddress(true); Charset charset = Charset.forName("UTF-8"); cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(charset))); // Bind acceptor.bind(new InetSocketAddress(port), new ReverseProtocolHandler(), cfg); }
public void start() throws Exception { acceptor = new NioSocketAcceptor(); // Prepare the configuration ((NioSocketAcceptor) acceptor).setReuseAddress(true); Charset charset = Charset.forName("UTF-8"); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(charset))); acceptor.setHandler(new Mina2ReverseProtocolHandler()); // Bind acceptor.bind(new InetSocketAddress(port)); }
private void startMinaServer() { initNotify(); // serverThread = new Thread(new Runnable() { // @Override // public void run() { // // } // }); // serverThread.start(); try{ //创建一个非阻塞的server端的Socket acceptor = new NioSocketAcceptor(); //设置过滤器(使用mina提供的文本换行符编解码器) acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue() ) ) ); //自定义的编解码器 //acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CharsetCodecFactory())); //设置读取数据的换从区大小 acceptor.getSessionConfig().setReadBufferSize(2048); //读写通道10秒内无操作进入空闲状态 acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); //为接收器设置管理服务 acceptor.setHandler(new ServerHandler()); //绑定端口 acceptor.bind(new InetSocketAddress(PORT)); LogUtils.i("服务器启动成功... 端口号:"+PORT); }catch (Exception e){ LogUtils.e("服务器异常.."+e); } }
/** * <p>startServer</p> * * @throws java.lang.Exception if any. */ public void startServer() throws Exception { m_acceptor = new NioSocketAcceptor(); m_acceptor.getFilterChain().addLast("logger", new LoggingFilter()); m_acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(CHARSET_UTF8))); m_acceptor.setHandler(getServerHandler()); m_acceptor.getSessionConfig().setReadBufferSize(getBufferSize()); m_acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, getIdleTime()); ((NioSocketAcceptor) m_acceptor).setReuseAddress(true); m_acceptor.bind(new InetSocketAddress(getPort())); }
public static void main(String[] args) throws Throwable { IoBuffer.setUseDirectBuffer(false); IoBuffer.setAllocator(new SimpleBufferAllocator()); SocketConnector connector = new NioSocketConnector(Runtime.getRuntime().availableProcessors() + 1); // Configure the service. connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); connector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newFixedThreadPool(MAX_THREADS))); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); connector.getFilterChain().addLast("logger", new LoggingFilter()); SMTPSessionHandler handler = new SMTPSessionHandler("localhost"); connector.setHandler(handler); while (true) { try { for (int i = 0; i < 10; i++) connector.connect(new InetSocketAddress(HOSTNAME, PORT)); Thread.sleep(100); } catch (RuntimeIoException e) { System.err.println("Failed to connect."); e.printStackTrace(); Thread.sleep(1000); } } }
protected void startListening(boolean activateSSL) { try { this.acceptor = new NioSocketAcceptor(); ((NioSocketAcceptor)this.acceptor).setReuseAddress(true); if(activateSSL) { //Makes the tcp connection protected with SSL SslFilter sslFilter = new SslFilter(this.getSSLContext()); this.acceptor.getFilterChain().addLast("ssl", sslFilter); } // //TextLineCodecFactory textLine = new TextLineCodecFactory(Charset.forName("UTF-8")); TextLineCodecFactory textLine = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.UNIX.getValue(), "EOF"); textLine.setDecoderMaxLineLength(Integer.MAX_VALUE); textLine.setEncoderMaxLineLength(Integer.MAX_VALUE); ProtocolCodecFilter codecFilter = new ProtocolCodecFilter(textLine); this.acceptor.getFilterChain().addLast( "codec", codecFilter); // this.acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter()); //Add Custom filters here if(this.payloadFilter != null) { this.acceptor.getFilterChain().addLast("payloadFilter", this.payloadFilter); } if(this.requestFilter != null) { this.acceptor.getFilterChain().addLast("requestFilter", this.requestFilter); } if(this.transactionFilter != null) { this.acceptor.getFilterChain().addLast("transactionFilter", this.transactionFilter); } if(this.authenticationFilter != null) { this.acceptor.getFilterChain().addLast("authenticationFilter", this.authenticationFilter); } //session specific configuration this.acceptor.getSessionConfig().setBothIdleTime(10); this.acceptor.setHandler(this.handler); this.acceptor.bind(new InetSocketAddress(this.port)); log.info("--------------------------------------------"); log.info("Mobile Data Server successfully loaded on port ("+this.port+")....."); log.info("--------------------------------------------"); } catch(Exception e) { log.error(this, e); this.stop(); throw new RuntimeException(e); } }
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(); }
private void start() { Config conf = ConfigFactory.load(); String check_server_beat_ip = conf.getString("check_server_beat_ip"); int check_server_beat_port = conf.getInt("check_server_beat_port"); if (U.isEmpty(check_server_beat_ip)) { log.error("BeatClient 连接心跳服务器 没有配置!"); return; } NioSocketConnector connector = new NioSocketConnector(); DefaultIoFilterChainBuilder chain = connector.getFilterChain(); chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(new BeatHanlder()); connector.setConnectTimeoutMillis(15 * 1000); // 设置连接超时 ,15秒 connector.setConnectTimeoutCheckInterval(300); long waitTimeConnect = 2 * 1000; final long waitTimeMAX = 30 * 1000; final long waitTimeSpace = 2 * 1000; for (;;) { try { ConnectFuture cf = connector .connect(new InetSocketAddress(check_server_beat_ip, check_server_beat_port)); cf.awaitUninterruptibly(); IoSession session = cf.getSession();// 获取会话 if (session.isConnected()) { log.info("BeatClient 连接心跳服务器OK IP:" + check_server_beat_ip + ",PORT:" + check_server_beat_port); break; } Thread.sleep(waitTimeConnect); } catch (Exception e) { log.error("ERROR_connect :" + e.getMessage()); try { Thread.sleep(waitTimeConnect); } catch (InterruptedException e1) { } } finally { waitTimeConnect += waitTimeSpace; if (waitTimeConnect > waitTimeMAX) { waitTimeConnect = waitTimeSpace; } } } }
@Override public void sessionOpened(IoSession session) throws Exception { session.getFilterChain().addFirst("textFilter", new ProtocolCodecFilter(new TextLineCodecFactory())); session.setAttribute("session", new UpdateSession(type, session)); }
public void init() { IoConnector connector = new NioSocketConnector(); connector.getSessionConfig().setReadBufferSize(2048); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(new MinaChatClientHandler(listener)); ConnectFuture future = connector.connect(new InetSocketAddress(host, port)); future.awaitUninterruptibly(); if (!future.isConnected()) { return; } session = future.getSession(); }
/** * Default constructor. */ public void connectAndSend() { LOGGER.debug(ipAddress +":"+ portNo); SocketAddress address = parseSocketAddress(ipAddress +":"+ portNo); LOGGER.debug("UDPClient::UDPClient"); LOGGER.debug("Created a datagram connector"); connector = new NioDatagramConnector(); LOGGER.debug("Setting the handler"); connector.setHandler(this); IoFilter LOGGING_FILTER = new LoggingFilter(); IoFilter CODEC_FILTER = new ProtocolCodecFilter( new TextLineCodecFactory()); connector.getFilterChain().addLast("mdc", new MdcInjectionFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.getFilterChain().addLast("logger", LOGGING_FILTER); LOGGER.debug("About to connect to the server..."); ConnectFuture future1 = connector.connect(address); future1.awaitUninterruptibly(); if (!future1.isConnected()) { return; } session = future1.getSession(); // try { //sendData(fileSignature); /* UdpMessage m = new UdpMessage(); m.setSequence(0); m.setFileSignature(fileSignature); session.write(m);*/ RequestSignatureMessage signatureMessage = new RequestSignatureMessage(); FileSignature fileSignature; try { fileSignature = new FileSignature(query); signatureMessage.setSequence(0); signatureMessage.setFileSignature(fileSignature); signatureMessage.setMatches(matches); System.out.println("Sending the query: " + query); System.out.println("[PeerlessSendUdpMessageSupport] file signature" + fileSignature); session.write(signatureMessage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //fileSignature.setFileSignature(query); }
public boolean connect(NioSocketConnector connector, SocketAddress address, boolean useSsl) { if (session != null && session.isConnected()) { throw new IllegalStateException( "Already connected. Disconnect first."); } try { IoFilter LOGGING_FILTER = new LoggingFilter(); IoFilter CODEC_FILTER = new ProtocolCodecFilter( new TextLineCodecFactory()); connector.getFilterChain().addLast("mdc", new MdcInjectionFilter()); //connector.getFilterChain().addLast("codec", CODEC_FILTER); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.getFilterChain().addLast("logger", LOGGING_FILTER); if (useSsl) { SSLContext sslContext = BogusSslContextFactory .getInstance(false); SslFilter sslFilter = new SslFilter(sslContext); sslFilter.setUseClientMode(true); connector.getFilterChain().addFirst("sslFilter", sslFilter); } connector.setHandler(handler); ConnectFuture future1 = connector.connect(address); future1.awaitUninterruptibly(); if (!future1.isConnected()) { return false; } session = future1.getSession(); login(); return true; } catch (Exception e) { return false; } }
public boolean register(NioSocketConnector connector, SocketAddress address, String name, String id, String password, String question, String passwordReminder, boolean useSsl) { System.out.println("This is address: " + address); if (session != null && session.isConnected()) { throw new IllegalStateException( "Already connected. Disconnect first."); } try { IoFilter LOGGING_FILTER = new LoggingFilter(); IoFilter CODEC_FILTER = new ProtocolCodecFilter( new TextLineCodecFactory()); connector.getFilterChain().addLast("mdc", new MdcInjectionFilter()); //connector.getFilterChain().addLast("codec", CODEC_FILTER); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.getFilterChain().addLast("logger", LOGGING_FILTER); if (useSsl) { SSLContext sslContext = BogusSslContextFactory .getInstance(false); SslFilter sslFilter = new SslFilter(sslContext); sslFilter.setUseClientMode(true); connector.getFilterChain().addFirst("sslFilter", sslFilter); } connector.setHandler(handler); ConnectFuture future1 = connector.connect(address); future1.awaitUninterruptibly(); if (!future1.isConnected()) { return false; } session = future1.getSession(); register m = new register(); m.setSequence(0); m.setCommand("REGISTER"); m.setUserId(id); m.setpassword(password); m.setQuestion(question); m.setpasswordReminder(passwordReminder); session.write(m); /*session.write("REGISTER " + id + CommonConfig.delimeter + name + CommonConfig.delimeter + password + CommonConfig.delimeter + question + CommonConfig.delimeter + passwordReminder);*/ return true; } catch (Exception e) { e.printStackTrace(); return false; } }
public void init() 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 MinaChatServerHandler()); acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 600); acceptor.bind(new InetSocketAddress(port)); }