1.accept:偵聽並接受此套接字的鏈接;此方法在鏈接傳入以前一直阻塞。java
2.setSoTimeout(timeout)方法的做用時設置超時時間,經過指定超時timeout值啓用/禁用超時功能,以ms爲單位。socket
必須在進入阻塞前調用這個方法,才能生效,一旦超時,程序會觸發SocketTimeoutException異常;默認值是0即永遠等待。spa
Server.java.net
package com.company.s7; import java.io.IOException; import java.net.ServerSocket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket=new ServerSocket(8000); System.out.println(serverSocket.getSoTimeout()); serverSocket.setSoTimeout(4000); System.out.println(serverSocket.getSoTimeout()); System.out.println(); System.out.println("begin "+System.currentTimeMillis()); serverSocket.accept(); System.out.println(" end "+System.currentTimeMillis()); }catch (IOException e){ e.printStackTrace(); } } }
Client.javacode
package com.company.s7; import java.io.IOException; import java.net.Socket; public class Client { public static void main(String[] args) { try { System.out.println("client begin "+System.currentTimeMillis()); Socket socket=new Socket("localhost",8000); System.out.println("client end "+System.currentTimeMillis()); }catch (IOException e){ e.printStackTrace(); System.out.println("catch "+System.currentTimeMillis()); } } }
backlog參數含義:server
容許接受客戶端鏈接請求的個數。blog
若是隊列已滿,則拒接該鏈接。隊列
blacklog參數若是小於等於0,則使用默認值50;get
Server.javaio
package com.company.s71; import javax.sound.midi.Soundbank; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException, InterruptedException { ServerSocket serverSocket=new ServerSocket(8088,3); //sleep(5000)的做用是不讓ServerSocket調用accept()方法, //而是由客戶端Socket先發奇10個鏈接請求 //而後在執行accept方法時只能接收3個鏈接 Thread.sleep(5000); System.out.println("accept1 begin"); Socket socket1=serverSocket.accept(); System.out.println("accept1 end"); System.out.println("accept2 begin"); Socket socket2=serverSocket.accept(); System.out.println("accept2 end"); System.out.println("accept3 begin"); Socket socket3=serverSocket.accept(); System.out.println("accept3 end"); System.out.println("accept4 begin"); Socket socket4=serverSocket.accept(); System.out.println("accept4 end"); System.out.println("accept5 begin"); Socket socket5=serverSocket.accept(); System.out.println("accept5 end"); socket1.close(); socket2.close(); socket3.close(); socket4.close(); socket5.close(); serverSocket.close(); } }
Client.java
package com.company.s71; import java.io.IOException; import java.net.Socket; public class Client { public static void main(String[] args) throws IOException { Socket socket1=new Socket("localhost",8088); Socket socket2=new Socket("localhost",8088); Socket socket3=new Socket("localhost",8088); Socket socket4=new Socket("localhost",8088); // Socket socket5=new Socket("localhost",8088); } }
先啓動server.java,而後快速的啓動client.java;
可是讓我很奇怪的是服務端啓動五秒以後,再啓動客戶端,反而能正確的執行;
若是由知道的人,請留言區告知,謝謝。