简体   繁体   English

serversocket.accept()何时会引发异常? 【JAVA]

[英]When do serversocket.accept() throws an exception? [java]

I want to have a counter of how much incoming connections I have per second. 我想要一个计数器,以了解我每秒有多少个传入连接。 That means, I have made a loop like this one: 那意味着,我做了这样的循环:

int incomingConnections;
while(true) {
  try {
     Socket socket = serverSocket.accept();
     incomingConnections++;
  } catch (Exception ex) {
  }

Before, I started a TimerTask like this: 之前,我启动了一个TimerTask,如下所示:

new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("TimerTask: " + incominConnections + " incoming Connections while the last second.");
                incominConnections = 0;
            }
        }, 0, 1000);

What do I need to do, because I want the int only to count when it accepts a connection succesfull, not everytime it iterates the loop. 我需要做什么,因为我希望int仅在它接受连接成功时才进行计数,而不是每次迭代循环时都进行计数。 Any help out there? 有什么帮助吗? Thx 谢谢

Your code already does what you want. 您的代码已经可以满足您的要求。

The Java documentation for ServerSocket.accept() states that it: ServerSocket.accept()的Java文档指出:

Listens for a connection to be made to this socket and accepts it. 监听与此套接字建立的连接并接受它。 The method blocks until a connection is made. 该方法将阻塞,直到建立连接为止。

So because the call to accept blocks, you will only ever increment your counter if a connection is successfully made. 因此,由于对accept的调用会阻塞,因此只有在成功建立连接后,您才会增加计数器的数量。

If an exception is thrown in the call to accept() you will enter the catch block, without executing the code that increments the counter. 如果对accept()的调用中引发了异常,则您将进入catch块,而无需执行增加计数器的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM