Esempio n. 1
0
  private void keepAliveFilterForIdleStatus(IdleStatus status) throws Exception {
    NioSocketConnector connector = new NioSocketConnector();
    KeepAliveFilter filter =
        new KeepAliveFilter(new ClientFactory(), status, EXCEPTION, INTERVAL, TIMEOUT);
    filter.setForwardEvent(true);
    connector.getFilterChain().addLast("keep-alive", filter);

    final AtomicBoolean gotException = new AtomicBoolean(false);
    connector.setHandler(
        new IoHandlerAdapter() {
          @Override
          public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            // cause.printStackTrace();
            gotException.set(true);
          }

          @Override
          public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            // Do nothing
          }
        });

    ConnectFuture future =
        connector.connect(new InetSocketAddress("127.0.0.1", port)).awaitUninterruptibly();
    IoSession session = future.getSession();
    assertNotNull(session);

    Thread.sleep((INTERVAL + TIMEOUT + 1) * 1000);

    assertFalse("got an exception on the client", gotException.get());

    session.close(true);
    connector.dispose();
  }
Esempio n. 2
0
  public void socketServer() {
    // 创建一个socket连接
    NioSocketConnector connector = new NioSocketConnector();
    // 消息核心处理器
    connector.setHandler(new MinaClientHanlder());
    // 设置链接超时时间
    connector.setConnectTimeoutCheckInterval(30);
    // 获取过滤器链
    DefaultIoFilterChainBuilder chain = connector.getFilterChain();
    ProtocolCodecFilter filter =
        new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")));
    // 添加编码过滤器 处理乱码、编码问题
    chain.addLast("objectFilter", filter);

    // 连接服务器,知道端口、地址
    ConnectFuture cf = connector.connect(new InetSocketAddress(App.address, App.bindPort));
    // 等待连接创建完成
    cf.awaitUninterruptibly();
    if (cf.isConnected()) {
      App.isConnected = true;
      System.out.println("等待连接断开");
      // 等待连接断开
      cf.getSession().getCloseFuture().awaitUninterruptibly();
    } else {
      System.out.println("连接断开");
      App.isConnected = false;
    }
    System.out.println("----dispose");
    connector.dispose();
    System.out.println("dispose----");
  }
Esempio n. 3
0
  private void init() {
    connector = new NioSocketConnector();
    bh = new BotHandler(username, password, roomId);
    connector.setHandler(bh);

    DefaultIoFilterChainBuilder chain = connector.getFilterChain();

    log.debug("connecing to the server...");
    ConnectFuture connFuture =
        connector.connect(
            new InetSocketAddress(ServerConfig.gameServerAddress, ServerConfig.gameServerPort));
    connFuture.awaitUninterruptibly();
  }
 public void doConnnect() {
   // 连结到服务器:
   ConnectFuture cf = connector.connect(new InetSocketAddress(remoteServerHost, remoteServerPort));
   cf.addListener(
       new IoFutureListener<ConnectFuture>() {
         public void operationComplete(ConnectFuture future) {
           if (future.isConnected()) {
             logger.info("连接成功:" + getServerInfo());
           } else {
             logger.error("连接失败:" + ",原因:" + future.getException());
             // 启动连接失败时定时重连
             scheduleConnect();
           }
         }
       });
 }
  /**
   * 根据host和port新建一个IoSession连接
   *
   * @param host 连接主机IP
   * @param port 连接端口
   * @param timeout 未收到数据超时时间/秒
   */
  @Override
  public void connect(String host, int port, int timeout) throws Exception {
    connector.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE, timeout);
    log.debug("超时时间:" + timeout + "秒");
    // 设置连接超时时间
    connector.setConnectTimeoutMillis(ExpressConstant.CONNECT_TIMEOUT);

    // 创建连接
    ConnectFuture future = connector.connect(new InetSocketAddress(host, port));

    // 等待连接创建完成
    future.awaitUninterruptibly();

    // 得到连接Session
    session = future.getSession();
    // 设置Session同步锁对象
    session.setAttribute(ExpressConstant.SESSION_LOCK, new LockExpress());
  }
Esempio n. 6
0
 /**
  * Title:
  *
  * <p>Desc:初始化客户端信息
  *
  * @param message
  * @throws UnsupportedEncodingException
  */
 public TongbuClient(Object message, String url, int port) {
   chain.addLast("logging", new LoggingFilter()); // 添加日志过滤器
   chain.addLast("myChin", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
   if (message instanceof String) {
     connector.setHandler(new ClientHandler((String) message));
   } else if (message instanceof CommEntity) {
     connector.setHandler(new ClientHandler((CommEntity) message));
   }
   connector.setConnectTimeoutMillis(10000);
   SocketSessionConfig cfg = connector.getSessionConfig();
   cfg.setUseReadOperation(true);
   IoSession session =
       connector.connect(new InetSocketAddress(url, port)).awaitUninterruptibly().getSession();
   ReadFuture readFuture = session.read();
   readFuture.awaitUninterruptibly();
   this.info = (CommResultInfo) readFuture.getMessage();
   session.close(true);
   session.getService().dispose();
 }
 private IoSession createSession(NioSocketConnector connector, InetSocketAddress socketAddress) {
   IoSession session;
   for (; ; ) {
     try {
       ConnectFuture future = connector.connect(socketAddress);
       future.awaitUninterruptibly();
       session = future.getSession();
       break;
     } catch (RuntimeIoException e) {
       logger.error("Error while obtaining sensor server session", e);
       try {
         Thread.sleep(5000);
       } catch (InterruptedException e1) {
         logger.error("Error while sleeping", e);
       }
     }
   }
   return session;
 }
Esempio n. 8
0
  private CommandMinaClient() throws java.net.ConnectException {
    NioSocketConnector connector = new NioSocketConnector();
    // 创建接收数据的过滤器
    DefaultIoFilterChainBuilder chain = connector.getFilterChain();
    // 设定这个过滤器将以对象为单位读取数据
    ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
    // 设定服务器端的消息处理器:一个SamplMinaServerHandler对象,
    chain.addLast("objectFilter", filter);

    // 设定服务器端的消息处理器:一个 SamplMinaServerHandler 对象,
    connector.setHandler(new CommandMinaClientHanlder());
    // Set connect timeout.
    connector.setConnectTimeoutCheckInterval(30);
    // 连结到服务器:
    ConnectFuture cf = connector.connect(new InetSocketAddress("159.226.95.156", 9900));
    // Wait for the connection attempt to be finished.
    cf.awaitUninterruptibly();

    session = cf.getSession();
  }
Esempio n. 9
0
  public void connect(InetAddress ia, int port) {
    connector = new NioSocketConnector();
    connector
        .getFilterChain()
        .addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    if (logger.isDebugEnabled()) {
      LoggingFilter logFilter = new LoggingFilter();
      logFilter.setMessageSentLogLevel(LogLevel.DEBUG);
      logFilter.setMessageReceivedLogLevel(LogLevel.DEBUG);
      connector.getFilterChain().addLast("logger", logFilter);
    }
    connector.setHandler(this);

    ConnectFuture future = connector.connect(new InetSocketAddress(ia, port));
    future.awaitUninterruptibly();
    if (!future.isConnected()) {
      logger.error("Connection failed");
    }
    session = future.getSession();
  }
  @Test
  public void testWriteUsingSocketTransport() throws Exception {
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setReuseAddress(true);
    SocketAddress address =
        new InetSocketAddress("localhost", AvailablePortFinder.getNextAvailable());

    NioSocketConnector connector = new NioSocketConnector();

    // Generate 4MB of random data
    byte[] data = new byte[4 * 1024 * 1024];
    new Random().nextBytes(data);

    byte[] expectedMd5 = MessageDigest.getInstance("MD5").digest(data);

    M message = createMessage(data);

    SenderHandler sender = new SenderHandler(message);
    ReceiverHandler receiver = new ReceiverHandler(data.length);

    acceptor.setHandler(sender);
    connector.setHandler(receiver);

    acceptor.bind(address);
    connector.connect(address);
    sender.latch.await();
    receiver.latch.await();

    acceptor.dispose();

    assertEquals(data.length, receiver.bytesRead);
    byte[] actualMd5 = receiver.digest.digest();
    assertEquals(expectedMd5.length, actualMd5.length);
    for (int i = 0; i < expectedMd5.length; i++) {
      assertEquals(expectedMd5[i], actualMd5[i]);
    }
  }
Esempio n. 11
0
 public void connect(String host, int port, CmdListener cmdListener) {
   final CmdListener fCmdListener = cmdListener;
   // --start
   // IoBuffer.setUseDirectBuffer(false);
   // IoBuffer.setAllocator(new QSIoBufferAllocater());
   // --end
   ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
   connectFuture.addListener(
       new IoFutureListener<ConnectFuture>() {
         public void operationComplete(ConnectFuture future) {
           if (!future.isConnected()) {
             fCmdListener.onException(new Exception("连接超时"));
           } else {
             future.getSession().setAttribute("CmdListener", fCmdListener);
             future
                 .getSession()
                 .getConfig()
                 .setIdleTime(IdleStatus.WRITER_IDLE, fCmdListener.getWriteTimeout());
             future.getSession().getConfig().setReadBufferSize(3000);
             future.getSession().write(fCmdListener.getCmdResuest());
           }
         }
       });
 }