Exemplo n.º 1
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----");
  }
  /**
   * Attempts a connection to the world model.
   *
   * @param timeout the connection timeout value in milliseconds.
   * @return {@code true} if the attempt succeeds, else {@code false}.
   */
  protected boolean _connect(long timeout) {
    log.debug("Attempting connection...");
    ConnectFuture connFuture = this.connector.connect(new InetSocketAddress(this.host, this.port));
    if (!connFuture.awaitUninterruptibly(timeout)) {
      log.warn(
          "Unable to connect to world model after {}ms.", Long.valueOf(this.connectionTimeout));
      return false;
    }
    if (!connFuture.isConnected()) {
      log.debug("Failed to connect.");
      return false;
    }

    try {
      log.debug("Attempting connection to {}:{}.", this.host, Integer.valueOf(this.port));
      this.session = connFuture.getSession();
    } catch (RuntimeIoException ioe) {
      log.error(
          String.format(
              "Could not create session to World Model (C) %s:%d.",
              this.host, Integer.valueOf(this.port)),
          ioe);
      return false;
    }
    return true;
  }
Exemplo n.º 3
0
 public void run() {
   while (true) {
     MinaNode node = (MinaNode) BisonContext.this.connectQueue.poll();
     if ((node == null) && (BisonContext.this.connectQueue.size() == 0)) {
       BisonContext.this.processor = null;
       break;
     }
     ConnectFuture cf = BisonContext.this.connector.connect(node.getRemoteAddress());
     cf.awaitUninterruptibly();
     if (!cf.isConnected()) {
       BisonContext.this.logger.info("建立连接失败 " + node.toString());
       try {
         if (BisonContext.this.connectQueue.size() == 0) Thread.sleep(5000L);
         else Thread.sleep(1000L);
       } catch (Exception localException) {
       }
       BisonContext.this.connectQueue.offer(node);
       continue;
     }
     cf.getSession().setAttribute(SESSION_NODE_KEY, node);
     node.setSession(cf.getSession());
     node.setConnected(true);
     BisonContext.this.logger.info("建立连接成功 " + node.toString());
   }
 }
Exemplo n.º 4
0
 public boolean send(String message) {
   if (future.isConnected()) {
     // 等待连接创建完成
     future.awaitUninterruptibly();
     // 获取当前session
     session = future.getSession();
     session.write(message);
     return true;
   } else {
     return false;
   }
 }
Exemplo n.º 5
0
 private void init() {
   connector = new NioSocketConnector();
   connector.setConnectTimeoutMillis(15000);
   connector.setHandler(this);
   JsonProtocalCodecFactory factory = new JsonProtocalCodecFactory(Charset.forName("UTF-8"));
   connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
   ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
   connectFuture.awaitUninterruptibly(); // 同步,等待,直到连接完成
   if (connectFuture.isDone()) {
     if (!connectFuture.isConnected()) { // 若在指定时间内没连接成功,则抛出异常
       connector.dispose(); // 不关闭的话会运行一段时间后抛出,too many open
       connector = null;
     }
   }
   lastTime = System.currentTimeMillis();
 }
Exemplo n.º 6
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();
  }
 @Override
 public boolean isConnected() {
   return connectFuture.isConnected() && connectFuture.getSession().isConnected();
 }
Exemplo n.º 8
0
 /*     */ public void startup() /*     */ {
   /*     */ try
   /*     */ {
     /*  77 */ this.connector = new NioSocketConnector();
     /*  78 */ this.connector.setConnectTimeoutMillis(30000L);
     /*  79 */ this.connector
         .getFilterChain()
         .addLast("codec", new ProtocolCodecFilter(new JT808CodecFactory()));
     /*  80 */ this.connector.setHandler(this.handler);
     /*     */
     /*  82 */ ConnectFuture future = this.connector.connect(this.address);
     /*  83 */ future.awaitUninterruptibly();
     /*  84 */ if ((future.isDone()) && /*  85 */ (!future.isConnected())) {
       /*  86 */ this.connector.dispose();
       /*  87 */ log.error("未在时限内建立连接");
       /*  88 */ return;
       /*     */ }
     /*     */
     /*  91 */ this.session = future.getSession();
     /*     */
     /*  93 */ log.info("try to connect " + this.address);
     /*     */
     /*  95 */ if (this.sendThread == null) {
       /*  96 */ this.sendThread =
           new Thread(
               new Runnable()
               /*     */ {
                 /*     */ public void run() {
                   /*  99 */ long outmemorytime = 0L;
                   /*     */ while (true)
                     /*     */ try {
                       /* 102 */ Thread.sleep(10L);
                       /* 103 */ DistributeClient.this.write(
                           (UnitPackJT808) DistributeClient.this.distributeQueue.poll());
                       /*     */
                       /* 105 */ if ((outmemorytime == 0L)
                           && (DistributeClient.this.distributeMsgId.size()
                               > Constants.OUTOFMEMORY / 2)) {
                         /* 106 */ outmemorytime = System.currentTimeMillis();
                         /*     */ }
                       /* 108 */ if (outmemorytime != 0L)
                         /* 109 */ if (DistributeClient.this.distributeMsgId.size()
                             >= Constants.OUTOFMEMORY) {
                           /* 110 */ DistributeClient.log.info("drop message!");
                           /* 111 */ DistributeClient.this.distributeQueue.clear();
                           /* 112 */ outmemorytime = 0L;
                           /*     */ }
                         /* 114 */ else if (System.currentTimeMillis() - outmemorytime > 300000L) {
                           /* 115 */ DistributeClient.log.info("drop message!");
                           /* 116 */ DistributeClient.this.distributeQueue.clear();
                           /* 117 */ outmemorytime = 0L;
                           /*     */ }
                       /*     */ }
                     /*     */ catch (Exception e)
                     /*     */ {
                       /* 122 */ DistributeClient.this.rebuildSession();
                       /*     */ }
                   /*     */ }
                 /*     */ });
       /* 127 */ this.sendThread.start();
       /*     */ }
     /*     */ } catch (Exception e) {
     /* 130 */ rebuildSession();
     /*     */ }
   /*     */ }
Exemplo n.º 9
0
  /** {@inheritDoc} */
  @SuppressWarnings("resource")
  @Override
  public void sessionCreated(IoSession session) throws Exception {

    boolean isClient = session.getRemoteAddress().equals(forward);

    if (log.isDebugEnabled()) {
      log.debug("Is downstream: " + isClient);
      session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory));
    }

    session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server"));

    if (true) {

      String fileName =
          System.currentTimeMillis()
              + '_'
              + forward.getHostName()
              + '_'
              + forward.getPort()
              + '_'
              + (isClient ? "DOWNSTREAM" : "UPSTREAM");

      File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile();
      headersFile.createNewFile();

      File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile();
      rawFile.createNewFile();

      FileOutputStream headersFos = new FileOutputStream(headersFile);
      WritableByteChannel headers = headersFos.getChannel();

      FileOutputStream rawFos = new FileOutputStream(rawFile);
      WritableByteChannel raw = rawFos.getChannel();

      IoBuffer header = IoBuffer.allocate(1);
      header.put((byte) (isClient ? 0x00 : 0x01));
      header.flip();
      headers.write(header.buf());

      session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw));
    }

    // session.getFilterChain().addLast("logger", new LoggingFilter() );

    if (!isClient) {
      log.debug("Connecting..");
      IoConnector connector = new NioSocketConnector();
      connector.setHandler(this);
      ConnectFuture future = connector.connect(forward);
      future.awaitUninterruptibly(); // wait for connect, or timeout
      if (future.isConnected()) {
        if (log.isDebugEnabled()) {
          log.debug("Connected: {}", forward);
        }
        IoSession client = future.getSession();
        client.setAttribute(ProxyFilter.FORWARD_KEY, session);
        session.setAttribute(ProxyFilter.FORWARD_KEY, client);
      }
    }
    super.sessionCreated(session);
  }