SocketChannel在java中如何实现客户端

这篇文章主要介绍“SocketChannel在java中如何实现客户端”,在日常操作中,相信很多人在SocketChannel在java中如何实现客户端问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SocketChannel在java中如何实现客户端”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1、步骤

(1)创建SocketChannel实例,并将其配置为非阻塞模式,只有在SocketChannel实例中,任何I/O操作都是非阻塞的。

(2)使用connect()方法连接服务器,同时使用while循环连续检测和完全连接。在需要立即进行I/O操作之前,必须使用finishConnect()来完成连接过程。

(3)用ByteBuffer读写字节,假如SelectableChannel是一种非阻塞模式,那么它的I/O操作读写字节可能比实际字节少,甚至没有。因此,我们使用循环连续的读写来确保读写完成。

2、实例

public class NonBlockingTCPClient {
    public static void main(String[] args) {
        byte[] data = "hello".getBytes();
        SocketChannel channel = null;
        try {
            // 1. open a socket channel
            channel = SocketChannel.open();
            // adjust to be nonblocking
            channel.configureBlocking(false);
            // 2. init connection to server and repeatedly poll with complete
            // connect() and finishConnect() are nonblocking operation, both return immediately
            if (!channel.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8899))) {
                while (!channel.finishConnect()) {
                    System.out.print(".");
                }
            }
 
            System.out.println("Connected to server...");
 
            ByteBuffer writeBuffer = ByteBuffer.wrap(data);
            ByteBuffer readBuffer = ByteBuffer.allocate(data.length);
            int totalBytesReceived = 0;
            int bytesReceived;
            // 3. read and write bytes
            while (totalBytesReceived < data.length) {
                if (writeBuffer.hasRemaining()) {
                    channel.write(writeBuffer);
                }
                if ((bytesReceived = channel.read(readBuffer)) == -1) {
                    throw new SocketException("Connection closed prematurely");
                }
                totalBytesReceived += bytesReceived;
                System.out.print(".");
            }
            System.out.println("Server said: " + new String(readBuffer.array()));
        } catch (IOException e) {
            e.printstacktrace();
        } finally {
            // 4 .close socket channel
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                e.printstacktrace();
            }
        }
    }
}

到此,关于“SocketChannel在java中如何实现客户端”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程之家网站,小编会继续努力为大家带来更多实用的文章

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...