[英]Cannot set socket to nonblocking
I'm trying to get to grips with java networking and have a server talking to a client. 我试图与Java网络打交道,并让服务器与客户端通信。 I have found an error in trying to make a socket nonblocking.
我在尝试使套接字无阻塞时发现错误。 Could someone have a look through my code and try and find the bug?
有人可以浏览我的代码,然后尝试查找错误吗?
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
serverSocket.configureBlocking(false);
System.out.println("Server started");
} catch (IOException e) {
System.out.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening){
Socket s = serverSocket.accept();
long id = clients_id++;
ServerThread st = new ServerThread(s, id);
addClient(id, st);
st.start();
}
serverSocket.close();
}
You are confusing two (given: rather confusing) concepts of Java IO: 您正在混淆Java IO的两个(给定的:令人困惑的)概念:
If you plan on using non-blocking IO, you should definitely read through the documentation first and experiment a bit to understand that concept properly. 如果计划使用无阻塞IO,则一定要先通读文档,并做一些试验以正确理解该概念。 However once you do understand it, it allows you to write very fast IO-code.
但是,一旦您了解了它,就可以编写非常快速的IO代码。
It's not a 'bug', it's just a compile error. 这不是一个“ bug”,只是一个编译错误。 You have invented a method that doesn't exist, so the compiler won't let you call it.
您已经发明了一种不存在的方法,因此编译器不会让您调用它。 See java.nio.channels.ServerSocketChannel.
请参阅java.nio.channels.ServerSocketChannel。 It does have a configureBlocking() method, as does SocketChannel.
与SocketChannel一样,它确实具有configureBlocking()方法。
However, given the code you have written, there is no reason to set non-blocking mode at all. 但是,鉴于您已编写的代码,根本没有理由设置非阻塞模式。 What you have written is a typical framework for a blocking-mode TCP server.
您所写的是阻塞模式TCP服务器的典型框架。
Also, when you get an exception, don't just print a message of your own devising. 另外,当您遇到异常时,不要只打印自己设计的消息。 Print the one that comes with the exception.
打印异常随附的内容。
NIO is blocking by default so you don't need to set it. NIO默认情况下处于阻止状态,因此您无需进行设置。
I use blocking NIO and I suggest using that unless you have thousands of connections. 我使用阻塞NIO,除非您有成千上万个连接,否则我建议使用该功能。
What I suggest you do is use a thread pool like a ExecutorService. 我建议您做的是使用像ExecutorService这样的线程池。
I have found an error in trying to make a socket nonblocking.
我在尝试使套接字无阻塞时发现错误。
Since you haven't said what the error is, I suspect the error is not in the code you provided. 由于您没有说明错误是什么,我怀疑您提供的代码中没有该错误。
Why do you want to make it non-blocking? 您为什么要使其不阻塞?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.