1 Star 2 Fork 1

peipeihh/blog

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
NoneBlockingNioServer.java 1.25 KB
Copy Edit Raw Blame History
package blocking;
import util.Logger;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* Created by huangyinhuang on 1/31/2018.
*/
public class NoneBlockingNioServer {
public static void main(String[] args) throws Exception {
// please note: configure channel blocking state as false
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
Logger.info("A server is started on port 9000");
ServerSocket serverSocket = server.socket();
serverSocket.bind(new InetSocketAddress(9000));
// please note: server.accept() will not block current thread
// Accept method will return null directly if no client is connected
SocketChannel channel = null;
int count = 0;
while (channel == null) {
Logger.info("The server is trying to connect client, count=" + count++);
channel = server.accept();
Thread.sleep(500);
}
Logger.printClientInfo(channel);
Logger.info("Is connected: " + channel.isConnected());
channel.close();
server.close();
Logger.info("the end");
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/pphh/blog.git
git@gitee.com:pphh/blog.git
pphh
blog
blog
master

Search