[英]How to make an accepted socket non-blocking in java
我接受來自客戶端的連接,然后將連接的套接字傳遞給另一個對象,但是,該套接字需要是非阻塞的。 我正在嘗試使用getChannel().configureBlocking(false)
但這似乎不起作用。 它需要是非阻塞的,因為下面的方法每100ms調用一次。 還有其他方法我應該做這個非阻塞? 謝謝你的幫助!
public void checkForClients() {
DataOutputStream out;
DataInputStream in;
Socket connection;
InetAddress tempIP;
String IP;
try {
connection = serverSocket.accept();
connection.getChannel().configureBlocking(false);
System.err.println("after connection made");
in = new DataInputStream(connection.getInputStream());
out = new DataOutputStream(connection.getOutputStream());
tempIP = connection.getInetAddress();
IP = tempIP.toString();
System.err.println("after ip string");
// create a new user ex nihilo
connectedUsers.add(new ConnectedUser(IP, null, connection, in, out));
System.err.println("after add user");
} catch (SocketTimeoutException e) {
System.err.println("accept timeout - continuing execution");
} catch (IOException e) {
System.err.println("socket accept failed");
}
}
兩件事情:
ServerSocket
? 多客戶端服務器的基本結構是:
while (true) {
// accept connections
// spawn thread to deal with that connection
}
如果問題是在accept()
調用上阻塞,那么這就是accept()
所做的:它會阻塞等待連接。 如果這是一個問題,我建議你有一個單獨的線程來接受連接。
請參閱編寫套接字的服務器端 。
我希望你的代碼阻止接受調用,永遠不會進入configureBlocking調用。
我通常為每個套接字連接分離一個單獨的線程,並讓它阻塞,直到實際建立/接受連接。這允許主線程在等待客戶端連接時繼續解除阻塞。
如果你正在尋找非阻塞的sokets,我的建議是使用選擇器和ServerSocketChannels與NIO包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.