摆脱老派:我正在使用 Java SE 5(或 java v1.5)(请不要告诉我升级,因为对于我正在处理的[这是私人的]我需要使用这个版本的 java )。
我需要帮助设置 Web 客户端/服务器应用程序。我在网上寻找的每个变体都缩小到使用 websockets/sockets,但是我使用的 java 版本还没有套接字。
有谁有关于设置不使用套接字的客户端/服务器模型应用程序的教程,或者一些可以为我指明正确方向的示例代码?
编辑:
好吧,显然我的 java 版本确实有套接字。我会进一步研究一下。然而,现在我只是好奇,如何创建一个不使用套接字的java服务器?
你需要插座。它们充当连接的端点 https://en.m.wikipedia.org/wiki/Network_socket。不过,您可以使用阻塞的替代方案Socket
and 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
}
}
}
}
使用选择器(可选,但推荐)
你可以使用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
支持通过接受isAcceptable()
,通过阅读isReadable()
并通过写作isWritable()
,因此您可以在同一线程上处理所有 3 个。
这是使用 NIO 接受连接的基本示例。我强烈建议您多研究一下,以便更好地了解事情是如何运作的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)