JAVA Socket 編程學習筆記(一)

 1. Socket 通訊簡介及模型html

  Java Socket 可實現客戶端--服務器間的雙向實時通訊。java.net包中定義的兩個類socket和ServerSocket,分別用來實現雙向鏈接的client和server端。java

2. Socket 通訊實現方法編程

  2.1  服務器端(非多線程)    服務器

  1. 用指定的端口實例化一個SeverSocket對象。服務器就能夠用這個端口監遵從客戶端發來的鏈接請求。
  2. 調用ServerSocket的accept()方法,以在等待鏈接期間形成阻塞,監聽鏈接從端口上發來的鏈接請求。
  3. 利用accept方法返回的客戶端的Socket對象,進行讀寫IO的操做
  4. 關閉打開的流和Socket對象
/** 
 * 基於TCP協議的Socket通訊,實現用戶登陸,服務端 
*/ 
//一、建立一個服務器端Socket,即ServerSocket,指定綁定的端口,並監聽此端口 
ServerSocket serverSocket =newServerSocket(10086);//1024-65535的某個端口 
//二、調用accept()方法開始監聽,等待客戶端的鏈接 
Socket socket = serverSocket.accept(); 
//三、獲取輸入流,並讀取客戶端信息 
InputStream is = socket.getInputStream(); 
InputStreamReader isr =newInputStreamReader(is); 
BufferedReader br =newBufferedReader(isr); 
String info =null; 
while((info=br.readLine())!=null){ 
System.out.println("Hello,我是服務器,客戶端說:"+info); 
} 
socket.shutdownInput();//關閉輸入流 
//四、獲取輸出流,響應客戶端的請求 
OutputStream os = socket.getOutputStream(); 
PrintWriter pw = new PrintWriter(os); 
pw.write("Hello World!"); 
pw.flush(); 
 

//五、關閉資源 
pw.close(); 
os.close(); 
br.close(); 
isr.close(); 
is.close(); 
socket.close(); 
serverSocket.close(); 

  

  2.2  客戶端多線程

  1. 用服務器的IP地址和端口號實例化Socket對象。
  2. 調用connect方法,鏈接到服務器上。
  3. 得到Socket上的流,把流封裝進BufferedReader/PrintWriter的實例,以進行讀寫
  4. 利用Socket提供的getInputStream和getOutputStream方法,經過IO流對象,向服務器發送數據流
  5. 關閉打開的流和Socket。
//客戶端 
//一、建立客戶端Socket,指定服務器地址和端口 
Socket socket =newSocket("127.0.0.1",10086); 
//二、獲取輸出流,向服務器端發送信息 
OutputStream os = socket.getOutputStream();//字節輸出流 
PrintWriter pw =newPrintWriter(os);//將輸出流包裝成打印流 
pw.write("用戶名:admin;密碼:admin"); 
pw.flush(); 
socket.shutdownOutput(); 
//三、獲取輸入流,並讀取服務器端的響應信息 
InputStream is = socket.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
String info = null; 
while((info=br.readLine())!null){ 
 System.out.println("Hello,我是客戶端,服務器說:"+info); 
} 
 
//四、關閉資源 
br.close(); 
is.close(); 
pw.close(); 
os.close(); 
socket.close(); 

  2.2 服務器端 (多線程)socket

  1. 服務器端建立ServerSocket,循環調用accept()等待客戶端鏈接
  2. 客戶端建立一個socket並請求和服務器端鏈接
  3. 服務器端接受客戶端請求,建立socket與該客戶創建專線鏈接
  4. 創建鏈接的兩個socket在一個單獨的線程上對話
  5. 服務器端繼續等待新的鏈接
//服務器線程處理 和本線程相關的socket 
Socket socket =null; 
public serverThread(Socket socket){ 
this.socket = socket; 
} 
ServerSocket serverSocket =newServerSocket(10086); 
Socket socket =null; 
int count =0;//記錄客戶端的數量 
while(true){ 
socket = serverScoket.accept(); 
ServerThread serverThread =newServerThread(socket); 
 serverThread.start(); 
 count++; 
System.out.println("客戶端鏈接的數量:"+count); 
} 

叄考資料:this

 http://developer.51cto.com/art/201509/490775.htmurl

http://blog.csdn.net/benweizhu/article/details/6615542/spa

http://www.blogjava.net/Reg/archive/2010/07/17/326392.html.net

Java Tcp/IP+ Socket 編程

相關文章
相關標籤/搜索