使用Java.NET.ServerSocket能够方便的创建一个服务端套接字,这个类的构造函数有一个参数backlog。下面这段代码,在本机的8888端口上建立了一个套接字,backlog设置为5。

  1. // port:8888,backlog:5
  2. ServerSocket server = new ServerSocket(8888, 5);

下面的Client是我们的测试类,会创建30个socket连接。

  1. import java.net.Socket;
  2. public class Client {
  3. private static Socket[] clients = new Socket[30];
  4. public static void main(String[] args) throws Exception {
  5. for (int i = 1; i <= 30; i++) {
  6. clients[i-1] = new Socket("127.0.0.1", 8888);
  7. System.out.println("client connection:" + i);
  8. }
  9. }
  10. }

如果没有启动服务端套接字,那么直接运行Client会报错误:Connection refused: connect。

[plain] view plain copy
  1. Exception in thread "main" java.net.ConnectException: Connection refused: connect
  2. at java.net.DualStackPlainSocketImpl.connect0(Native Method)
  3. at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
  4. at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
  5. at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
  6. at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
  7. at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
  8. at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  9. at java.net.Socket.connect(Socket.java:579)
  10. at java.net.Socket.connect(Socket.java:528)
  11. at java.net.Socket.<init>(Socket.java:425)
  12. at java.net.Socket.<init>(Socket.java:208)

接下来我们启动Server端套接字,但是不调用accept()方法,也就是说不处理客户端的socket连接。

  1. import java.net.ServerSocket;
  2. public class Server {
  3. public static void main(String[] args) throws Exception{
  4. // port:8888,backlog:5
  5. ServerSocket server = new ServerSocket(8888, 5);
  6. while(true)
  7. {
  8. }
  9. }
  10. }

运行Client测试类,运行结果见下图:, 5);

  • int acceptCount = 0;
  • while(true)
  • {
  • Socket client = server.accept();
  • acceptCount++;
  • System.out.println("new connection has connected, num=" + acceptCount);
  • }
  • }
  • }
  • 运行测试类Client,服务端和客户端的运行结果如下:没有任何异常产生。, 5);

  • int acceptCount = 0;
  • while(true)
  • {
  • Socket client = server.accept();
  • acceptCount++;
  • System.out.println("new connection has connected, num=" + acceptCount);
  • Thread.sleep(2 * 1000);
  • }
  • }
  • }