码迷,mamicode.com
首页 > 编程语言 > 详细

java SocketChannel and ServerSocketChannel

时间:2017-12-25 17:04:47      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:www   connect   locking   configure   body   with   log   eth   返回   

1 SocketChannel

1.1 打开一个SocketChannel

SocketChannel socketChannel = SocketChannel.open();

socketChannel.connect(new InetSocketAddress("http://www.baidu.com", 80));

1.2 关闭一个SocketChannel

socketChannel.close();

1.3 读取一个SocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

int byteRead = socketChannel.read(buf);

2 ServerSocketChannel

2.1 ServerSocketChannel in blocking mode

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    serverSocketChannel.socket().bind(new InetSocketAddress(1111));

    while(true) {

        SocketChannel socketChannel = serverSocketChannel.accept();

        // do something with socketChannel.......

    }

2.2 ServerSocketChannel in non-blocking mode

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    serverSocketChannel.socket().bind(new InetSocketAddress(1111));

    serverSocketChannel.configureBlocking(false);

    while(true) {

        SocketChannel socketChannel = serverSocketChannel.accept();

        if (socketChannel != null)

        {

            // do something with socketChannel.......

        }

    }

在non-blocking mode时,没有人来connect的时候accept()就会直接返回。这也是non-blocking的意义所在,对于文件而言,总是可以读写的,不存在block一说,也就没有non-blocking mode了。

 

java SocketChannel and ServerSocketChannel

标签:www   connect   locking   configure   body   with   log   eth   返回   

原文地址:http://www.cnblogs.com/hustdc/p/8109785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!