Java NIO ServerSocketChannel


Java Nio 

1Java NIO Tutorial
2Java NIO Overview
3Java NIO Channel
4Java NIO Buffer
5Java NIO Scatter / Gather
6Java NIO Channel to Channel Transfers
7Java NIO Selector
8Java NIO FileChannel
9Java NIO SocketChannel
10Java NIO ServerSocketChannel
11Java NIO DatagramChannel
12Java NIO Pipe
13Java NIO vs. IO

Java NIO ServerSocketChannel

 
By Jakob Jenkov
 Connect with me: 
Rate article:
Share article:

A Java NIO ServerSocketChannel is a channel that can listen for incoming TCP connections, just like aServerSocket in standard Java Networking. The ServerSocketChannel class is located in thejava.nio.channels package.

Here is an example:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

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

while(true){
    SocketChannel socketChannel =
            serverSocketChannel.accept();

    //do something with socketChannel...
}

Opening a ServerSocketChannel

You open a ServerSocketChannel by calling the ServerSocketChannel.open() method. Here is how that looks:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

Closing a ServerSocketChannel

Closing a ServerSocketChannel is done by calling the ServerSocketChannel.close() method. Here is how that looks:

serverSocketChannel.close();

Listening for Incoming Connections

Listening for incoming connections is done by calling the ServerSocketChannel.accept() method. When theaccept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.

Since you are typically not interested in listening just for a single connection, you call the accept() inside a while-loop. Here is how that looks:

while(true){
    SocketChannel socketChannel =
            serverSocketChannel.accept();

    //do something with socketChannel...
}

Of course you would use some other stop-criteria than true inside the while-loop.

Non-blocking Mode

ServerSocketChannel can be set into non-blocking mode. In non-blocking mode the accept() method returns immediately, and may thus return null, if no incoming connection had arrived. Therefore you will have to check if the returned SocketChannel is null. Here is an example:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);

while(true){
    SocketChannel socketChannel =
            serverSocketChannel.accept();

    if(socketChannel != null){
        //do something with socketChannel...
        }
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值