有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java慢速socket。连接()

下面是客户端和服务器的源代码。 客户端只是(并发地)连接到服务器,并立即关闭连接。 当所有线程完成后,它将等待2分钟并再次连接。 我很困惑,有时一个简单的连接需要大约3秒钟! 大多数情况下,连接只需要大约0-32毫秒

这里是客户机的典型输出:

...
Connect 23 [ms]: 16
Connect 22 [ms]: 32
Connect 21 [ms]: 32
Connect 15 [ms]: 32
Connect 14 [ms]: 16
Connect 13 [ms]: 16
Connect 11 [ms]: 32
Connect 25 [ms]: 3016

这似乎只有在客户端和服务器位于不同主机上时才会发生。 Windows和linux的类似行为 Java 1.6.23

要启动服务器,需要2个参数: [端口][线程池大小]

要启动客户端,需要3个参数: [主机][端口][线程池大小]

对于这个示例,我对服务器使用了150个线程池大小,对客户端使用了25个线程池大小

有人能解释这种行为吗

----服务器-----

package de.test.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerApp {

   public static void main(String[] args) throws IOException {
      System.out.println("server running...");

      final int port = Integer.parseInt(args[0]);
      final int threads = Integer.parseInt(args[1]);
      final ExecutorService executorService = Executors
            .newFixedThreadPool(threads);
      ServerSocket serverSocket = new ServerSocket(port);
      while (true) {
         final Socket clientSocket = serverSocket.accept();

         executorService.execute(new Runnable() {
            @Override
            public void run() {
               try {
                  InputStream is = clientSocket.getInputStream();
                  int read = is.read();
                  if (read != -1) {
                     System.out.println("should not happen");
                  }
               } catch (IOException e) {
                  throw new RuntimeException(e);
               } finally {
                  close(clientSocket);
                  System.out.println("connection closed");
               }
            }

            private void close(final Socket connection) {
               try {
                  connection.close();
               } catch (IOException e1) {
                  throw new RuntimeException(e1);
               }
            };
         });
      }
   }
}

----客户-----

package de.test.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class ConnectApp {

   public static void main(String[] args) throws InterruptedException {
      final String host = args[0];
      final int port = Integer.parseInt(args[1]);
      final int THREAD_COUNT = Integer.parseInt(args[2]);

      final ExecutorService executorService = Executors
            .newFixedThreadPool(THREAD_COUNT);
      final AtomicLong threadCounter = new AtomicLong(0);
      while (true) {
         final CountDownLatch doneSignal = new CountDownLatch(THREAD_COUNT);
         for (int i = 0; i < THREAD_COUNT; i++) {
            executorService.execute(new Runnable() {
               @Override
               public void run() {
                  Socket socket = null;
                  try {
                     long start = System.currentTimeMillis();
                     socket = new Socket();

                     socket.setTcpNoDelay(true);
                     socket.connect(new InetSocketAddress(host, port));
                     System.out.println(socket.getTcpNoDelay());
                     long stop = System.currentTimeMillis();
                     System.out.println("Connect "
                           + threadCounter.incrementAndGet() + " [ms]: "
                           + (stop - start));
                  } catch (UnknownHostException e) {
                     throw new RuntimeException(e);
                  } catch (IOException e) {
                     throw new RuntimeException(e);
                  } finally {
                     close(socket);
                     doneSignal.countDown();
                  }

               }

               private void close(Socket socket) {
                  try {
                     if (socket != null)
                        socket.close();
                  } catch (IOException e1) {
                     throw new RuntimeException(e1);
                  }
               }
            });
         }
         doneSignal.await();
         System.out.println("Waiting 2 minutes...");
         Thread.sleep(1000 * 60 * 2);
      }
   }
}

共 (1) 个答案

  1. # 1 楼答案

    您的所有套接字都试图同时连接。由于它们都试图连接到同一个单线程服务器,其中一个将被接受,50个(默认情况下)将在待办事项中,重置可能无法连接或需要等待很长时间

    我建议尝试在尝试连接之间间隔40毫秒,看看这是否是问题所在

    顺便说一句:你只调用threadCounter.incrementAndGet(),为什么它会上下波动?你可以用

    for (int i = 0; i < THREAD_COUNT; i++) {
        final int threadCount = i;