aio client笔记

package aaaaaaClient;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * author: alibobo
 * description: 
 **/
public class FileSynClient {

    private AsynchronousSocketChannel client;

    // 连接服务器
    public void connect(String srcHost) {
        try {
            client = AsynchronousSocketChannel.open();
            client.setOption(StandardSocketOptions.TCP_NODELAY, true);
            Future<Void> connect = client.connect(new InetSocketAddress(srcHost, 20191));
            connect.get();
        } catch (IOException | InterruptedException | ExecutionException e) {
            System.out.println("连接服务器失败,确认服务器正常运行,以及ip设置是否正确.");
            e.printStackTrace();
        }
    }
    

    // 向服务器写数据数据
    private byte[] writeData(Object o) {
        // 为了得到返回的同步id, 此方法改成了成了同步等待
        byte[] jsonBytes = JSON.toJSONBytes(o);
        Future<Integer> write = client.write(ByteBuffer.wrap(jsonBytes));
        try {
            write.get();
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("发送数据失败,请确认数据格式是否正确");
            e.printStackTrace();
        }
        // 发送成功,开始接受服务器数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        Future<Integer> read = client.read(buffer);
        try {
            read.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("读取服务器响应信息有误");
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("服务器响应超时");
            e.printStackTrace();
        }
        // 读取成功,返回数据
        buffer.flip();
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes);
        buffer.clear();
        return bytes;

    }


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值