Ejemplo n.º 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;
  }
Ejemplo n.º 2
0
  public static void main(String[] args) {
    // 创建一个非阻塞的客户端程序
    IoConnector connector = new NioSocketConnector();
    // 设置链接超时时间
    connector.setConnectTimeout(30000);
    // 设置过滤器
    connector
        .getFilterChain()
        .addLast(
            "codec",
            new ProtocolCodecFilter(
                new TextLineCodecFactory(
                    Charset.forName("UTF-8"),
                    LineDelimiter.WINDOWS.getValue(),
                    LineDelimiter.WINDOWS.getValue())));

    // 添加业务逻辑处理器类
    connector.setHandler(new Demo1ClientHandler());
    IoSession session = null;
    try {
      ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT)); // 创建连接
      future.awaitUninterruptibly(); // 等待连接创建完成
      session = future.getSession(); // 获得session

      String sendPhone = "13681803609"; // 当前发送人的手机号码
      String receivePhone = "13721427169"; // 接收人手机号码
      String message = "测试发送短信,这个是短信信息哦,当然长度是有限制的哦....";
      String msg = sendPhone + ";" + receivePhone + ";" + message;

      session.write(msg); // 发送给移动服务端
    } catch (Exception e) {
      logger.error("客户端链接异常...", e);
    }

    session.getCloseFuture().awaitUninterruptibly(); // 等待连接断开
    connector.dispose();
  }