1、網絡通訊基礎java
網絡中存在不少的通訊實體,每個通訊實體都有一個標識符就是IP地址。服務器
而現實中每個網絡實體能夠和多個通訊程序同時進行網絡通訊,這就須要使用端口號進行區分。網絡
2、java中的基本網絡支持socket
一、IP地址使用InetAddress類來表示。測試
獲取InetAddress實例的兩個方法爲:大數據
(1)getByName(String host) 根據主機獲取對應的InetAddress對象spa
(2)getByAddress(byte[] addr)根據IP地址獲取InetAddress對象.net
二、InetAddress提供了三個方法來獲取InetAddress實例對應的IP地址和主機名code
(1)String getCanonicalHostName()獲取此IP地址的權限定域名對象
(2)String getHostAddress()獲取InetAddress實例對應的IP地址
(3)String getHostName()獲取此IP地址的主機名
此外InetAddress類使用getLocalHost()方法獲取本機IP地址對應的InetAddress實例,使用isReachable()方法測試是否能夠到達該地址。
3、java實現簡單的TCP/IP通訊
服務器端使用ServerSocket建立TCP服務器,使用accept()進行監聽,若是接收到客戶端請求則返回一個與客戶端對應的Socket,不然處於等待狀態。
客戶端根據服務器的IP,鏈接服務器。
服務器代碼:
import java.net.*; import java.io.*; /** 手機端代碼 手機端做爲服務器,獲取本身的ip地址,並顯示以供客戶端鏈接 */ public class phone_Server { public static void main(String[] args) throws IOException { //打印本機的IP地址 InetAddress address=InetAddress.getLocalHost(); System.out.println("本機的IP地址是"+address.getHostAddress()); // 建立一個ServerSocket,用於監聽客戶端Socket的鏈接請求 ServerSocket ss = new ServerSocket(30000); // 採用循環不斷接受來自客戶端的請求 while (true) { // 每當接受到客戶端Socket的請求,服務器端也對應產生一個Socket Socket s = ss.accept(); // 將Socket對應的輸出流包裝成PrintStream PrintStream ps = new PrintStream(s.getOutputStream()); // 進行普通IO操做 ps.println("您好,您收到了服務器的新年祝福!"); // 關閉輸出流,關閉Socket ps.close(); s.close(); } } }
客戶端代碼:
/** PC端代碼 PC做爲客戶端,根據服務器的IP地址和端口號鏈接服務器 */ import java.net.*; import java.io.*; public class PC_Client { public static void main(String[] args) throws IOException { //Socket socket = new Socket("127.0.0.1" , 30000); Socket socket = new Socket("192.168.47.1" , 30000);//這裏的IP地址填寫手機端服務器的IP地址 // 將Socket對應的輸入流包裝成BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 進行普通IO操做 String line = br.readLine(); System.out.println("來自服務器的數據:" + line); // 關閉輸入流、socket br.close(); socket.close(); } }
補充一點socket傳輸大數據的內容
因爲socket單次傳輸的數量是有必定的限制的,因此應該分批次傳輸和接受
能夠寫成這樣:
傳輸
DataOutputStream out = new DataOutputStream(socket.getOutputStream()); int start=0; while((start+1024)<data.length) { out.write(data, start,1024); start=start+1024; } if(start<data.length) { out.write(data, start,(data.length-start+1)); } //String str = new String(data); //out.writeUTF(str); }catch (Exception e) { Log.d(TAG, "文件傳輸異常"); }
接受
DataInputStream input = new DataInputStream(socket.getInputStream()); byte []buf=new byte[1024]; int readnum=0; while(true) { readnum=input.read(buf); if(readnum>0) { System.out.println(Arrays.toString(buf)); while((readnum=input.read(buf))>0) { System.out.println(Arrays.toString(buf)); } } }