如何在java中使接受的套接字无阻塞 [英] How to make an accepted socket non-blocking in java

查看:90
本文介绍了如何在java中使接受的套接字无阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在接受来自客户端的连接,然后将该连接的套接字传递给另一个对象,但是,该套接字需要是非阻塞的。我正在尝试使用 getChannel()。configureBlocking(false)但这似乎不起作用。它需要是非阻塞的,因为下面的方法每100ms调用一次。还有其他方法我应该做这个非阻塞?感谢您的帮助!

I'm accepting a connection from a client and then passing that connected socket off to another object, however, that socket needs to be non-blocking. I'm trying to use getChannel().configureBlocking(false) but that does not seem to be working. It needs to be non-blocking because this the method below is called every 100ms. Is there some other way that I should be making this non-blocking? Thanks for any help!

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");
  }
}


推荐答案

两个事情:


  1. 你为什么不使用 ServerSocket 如果你正在监听连接?

  2. 如果你想接受多个客户,你想要使用一个循环。

多元化的基本结构客户端服务器是:

The basic structure of a multi-client server is:

while (true) {
  // accept connections
  // spawn thread to deal with that connection
}

如果问题在 accept()调用,那就是 accept():它阻止等待连接。如果这是一个问题,我建议你有一个单独的线程来接受连接。

If the issue is blocking on the accept() call, well that's what accept() does: it blocks waiting for a connection. If that's an issue I suggest you have a separate thread to accept connections.

参见编写套接字的服务器端

这篇关于如何在java中使接受的套接字无阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆