ServerSocket构造函数中backlog参数的含义,可以接受客户端的数量
- - Java - 编程语言 - ITeye博客import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端
*/
public class Server {. int backlog = 3;//ServerSocket构造函数中的backlog参数.
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * 服务器端 */ public class Server { ServerSocket server = null; int serverPort = 9999; int backlog = 3;//ServerSocket构造函数中的backlog参数 public Server() throws Exception { server = new ServerSocket(serverPort, backlog); } public static void main(String[] args) throws Exception { Server server = new Server(); server.service(); // Thread.currentThread().sleep(1000*600);//持续600秒 } public void service() { int count = 1; while(true) { Socket socket = null; try { socket = server.accept(); System.out.println("new connection has connected,num:" + count++); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
import java.net.Socket; /** * 客户端 */ public class Client { public static void main(String[] args) throws Exception { for(int i=0; i<30; i++){ Socket socket = new Socket("127.0.0.1", 9999); System.out.println("client connection:" + (i+1)); } } }
import java.io.IOException; import java.net.ServerSocket; public class Test1 { public static void main(String[] args) { ServerSocket serverSocket = null; for(int i = 0; i < 65535; i++) { try { serverSocket = new ServerSocket(i); serverSocket.close(); } catch (IOException e) { //e.printStackTrace(); System.out.println("端口" + i + "已经被其他服务器进程占用"); } } } }