1 Star 2 Fork 1

peipeihh/blog

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
NoneBlockingNioServer.java 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
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

搜索帮助