示例#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----");
  }
 private NioSocketConnector setupConnector(IoHandlerAdapter handler) {
   NioSocketConnector connector = new NioSocketConnector();
   connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 300);
   connector.setConnectTimeoutCheckInterval(5);
   connector
       .getFilterChain()
       .addLast(
           "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
   connector.setHandler(handler);
   return connector;
 }
示例#3
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();
  }