예제 #1
0
  public boolean connect(CallBack cb) {

    // 创建一个socket连接
    connector = new NioSocketConnector();

    // 设置链接超时时间
    connector.setConnectTimeoutMillis(3000);
    // 获取过滤器链
    DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
    // 添加编码过滤器 处理乱码、编码问题
    filterChain.addLast(
        "codec",
        new ProtocolCodecFilter(
            new TextLineCodecFactory(
                Charset.forName("UTF-8"),
                LineDelimiter.WINDOWS.getValue(),
                LineDelimiter.WINDOWS.getValue())));
    /*
     * // 日志 LoggingFilter loggingFilter = new LoggingFilter();
     * loggingFilter.setMessageReceivedLogLevel(LogLevel.INFO);
     * loggingFilter.setMessageSentLogLevel(LogLevel.INFO);
     * filterChain.addLast("loger", loggingFilter);
     */
    // 消息核心处理器
    connector.setHandler(new MyIoHandlerAdapter(context, cb));

    // 连接服务器,知道端口、地址
    future = connector.connect(new InetSocketAddress("10.80.1.212", 9000));
    //		// 等待连接创建完成
    return true;
  }
예제 #2
0
 @SuppressWarnings({"rawtypes", "unchecked"})
 @Override
 protected void startConnector(String server, int port) {
   socketConnector = new NioSocketConnector();
   socketConnector.setHandler(ioHandler);
   ConnectFuture future = socketConnector.connect(new InetSocketAddress(server, port));
   future.addListener(
       new IoFutureListener() {
         public void operationComplete(IoFuture future) {
           try {
             // will throw RuntimeException after connection error
             future.getSession();
           } catch (Throwable e) {
             // if there isn't an ClientExceptionHandler set, a
             // RuntimeException may be thrown in handleException
             handleException(e);
             // to get here you must have an exception handler set
             socketConnector.dispose();
           }
         }
       });
   future.awaitUninterruptibly(CONNECTOR_WORKER_TIMEOUT);
 }
예제 #3
0
 public boolean close() {
   CloseFuture future = session.getCloseFuture();
   future.awaitUninterruptibly(1000);
   connector.dispose();
   return true;
 }
예제 #4
0
 @Override
 public void disconnect() {
   socketConnector.dispose();
   super.disconnect();
 }