抛弃老派:我正在使用 Java SE 5(或 java v1.5)(请不要告诉我升级,因为对于我正在处理的[这是私有(private)的]我需要使用这个java 版本)。
我需要帮助设置 Web 客户端/服务器应用程序。我在网上寻找的每个变体都缩小到使用 websockets/sockets,但是我使用的 java 版本还没有套接字。
是否有人有关于设置不使用套接字的客户端/服务器模型应用程序的教程,或者一些可以为我指明正确方向的示例代码?
编辑: 好吧,显然我的 java 版本确实有套接字。我会进一步研究一下。然而,现在我只是好奇,如何创建一个不使用套接字的java服务器?
最佳答案
你需要套接字。 They serve as the end-points to the connection 。不过,您可以使用阻塞 Socket
和 ServerSocket
实现的替代方案。
NIO(新IO)使用 channel 。它允许非阻塞 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
}
}
}
}
使用选择器(可选,但推荐)
您可以使用选择器
在读/写/接受之间切换,以便仅在无事可做时才允许阻塞(以消除多余的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 接受连接的基本示例。我强烈建议您深入研究一下,以更好地了解事物的工作原理。
关于java - 非基于套接字的 Java 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616774/