首页 > 代码库 > java网络编程4-ServerSocket

java网络编程4-ServerSocket

//端口号为0则系统随机分配端口,连接队列系统一般默认50,指过超过系统最大的就以系统为准
//如果客户端的连接超过连接队列,则会被主机拒绝
ServerSocket serverSocket=new ServerSocket(3344,20);


//指监听本机哪个ip
ServerSocket serverSocket=new ServerSocket(3344, 20, InetAddress.getByName("localhost"));


ServerSocket serverSocket=new ServerSocket();
//等客户端连接的超时时间,单位ms,默认为0不超时
serverSocket.setSoTimeout(1000);
//绑定某个端口,主要用于无参对象后,在bind方法前设置serverSocket的属性
serverSocket.bind(new InetSocketAddress(3344));
//阻塞程序,等待客户端连接,这个socket关闭不会关闭serverSocket
Socket socket= serverSocket.accept();
try {
  if(serverSocket!=null){
  //serverSocket关闭后关闭关联的socket
  serverSocket.close();
  }
} catch (Exception e) {
}


//获取绑定的ip,如果有多个网卡,则随机返回其中一个
System.out.println(serverSocket.getInetAddress());


//判断serverSocket是否绑定过某个端口
System.out.println(serverSocket.isBound());
//判断serverSocket是否关闭,没有绑定过端口的也会返回false
System.out.println(serverSocket.isClosed());
//正确判断serverSocket是否打开
System.out.println(serverSocket.isBound() && !serverSocket.isClosed());

java网络编程4-ServerSocket