• 技术文章 >java >java基础

    SocketChannel在java中实现客户端

    小妮浅浅小妮浅浅2021-06-08 09:57:36原创2878

    1、步骤

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

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

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

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    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中实现客户端的方法,希望对大家有所帮助。更多Java学习指路:Java基础

    本教程操作环境:windows7系统、java10版,DELL G3电脑。

    专题推荐:java socketchannel
    上一篇:java中SocketChannel是什么 下一篇:java中Selector如何选择通道

    相关文章推荐

    • Java中IO流复制文件的方法• Java对象流实现序列化的类• Java中RandomAccessFile类如何随机访问• Java中内核线程是什么?• Java中trim怎么用?• Java内存交互的规则• Java中Collection如何通过迭代器访问?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网