栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

非基于套接字的Java Server

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

非基于套接字的Java Server

您需要插座。它们充当连接的端点。虽然,您可以使用其他替代方法来阻止

Socket
ServerSocket
实现。

NIO(新IO)使用通道。它允许非阻塞的I / O:

class Server {     public static void main(String[] args) throws Exception {          ServerSocketChannel ssc = ServerSocketChannel.open();          ssc.configureBlocking(false);          while(true) {    SocketChannel sc = ssc.accept();    if(sc != null) {         //handle channel    }          }     }}

使用选择器 (可选,但推荐)

您可以使用a

Selector
在读取/写入/接受之间切换,以仅在无事可做时才进行阻止(以消除过多的CPU使用率)

class Server {     private static Selector selector;     public static void main(String[] args) throws Exception {          ServerSocketChannel ssc = ServerSocketChannel.open();          ssc.configureBlocking(false);          Selector selector = Selector.open();          ssc.register(selector, SelectionKey.OP_ACCEPT);          while(true) {    selector.select();    while(selector.iterator().hasNext()) {         SelectionKey key = selector.iterator().next();         if(key.isAcceptable()) {   accept(key);         }    }          }     }     private static void accept(SelectionKey key) throws Exception {          ServerSocketChannel channel = (ServerSocketChannel) key.channel();          SocketChannel sc = channel.accept();          sc.register(selector, OP_READ);     }}

SelectionKey
支持通过接受via
isAcceptable()
,读取via
isReadable()
和写入via
isWritable()
,因此您可以在同一线程上处理所有3个对象。

这是使用NIO接受连接的基本示例。我强烈建议您多加研究,以更好地了解事物的工作方式。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号