網絡編程

網絡概念

把多臺計算機經過物理線路鏈接起來,就造成了網絡。目的在於交換數據和共享信息。java

1.1 網絡通訊的三要素

【1】IP地址:惟一標識網絡上的每一臺計算機。兩臺計算機之間通訊的必備有素mysql

【2】端口號:計算機中應用的標號(表明一個應用程序)sql

0-1024系統使用或保留端口編程

常見端口:http:80 stmp: 25 ftp:21服務器

 有效端口0-65536,開發者能夠的端口是1025-65536之間。一些第三方引用如mysql:3306 oracle:1251。網絡

【3】通訊協議:通訊的規則 TCP,UDPoracle

1.2 網絡通訊模型(B)

 

 

特殊IPsocket

  • 0.0.0.0:本機
  • 127.0.0.1:本機迴環地址,用於本機測試
  • 255.255.255.255:當前子網,通常用於向當前子網廣播信息

 

1.3 InetAddress

InetAddress 表示IP地址。函數

 

 1 public class Test01 {
 2     public static void main(String[] args) {
 3         // 獲取本機IP地址
 4         InetAddress ip1;
 5         try {
 6             ip1 = InetAddress.getLocalHost();
 7             // USER-20180113BT/192.168.2.56
 8             System.out.println(ip1.toString());
 9             
10             // 獲取主機名稱
11             System.out.println(ip1.getHostName());
12             System.out.println(ip1.getHostAddress());
13             
14         } catch (UnknownHostException e) {
15             e.printStackTrace();
16         }
17     }
18 }

 

2. TCP 編程

TCP編程中,若是要完成通訊,通訊雙方必需要建立socket,經過socket完成通訊。測試

 

TCP通訊步驟

[1] 服務器啓動ServerSocket做爲通訊的Server端,等待客戶端鏈入。

[2] 客戶端建立Socket做爲通訊的Client端

[3] Client端鏈入Server端後創建可靠的雙向的持續性的點對點的通信鏈接,便可通訊。

 

案例:完成一次單向通訊。

服務器端

 1 package cn.sxt01.net01;
 2 
 3 import java.io.IOException;
 4 import java.io.OutputStream;
 5 import java.net.ServerSocket;
 6 import java.net.Socket;
 7 
 8 public class Server01 {
 9     public static void main(String[] args) {
10         
11         System.out.println("服務器啓動...");
12         
13         // 【1】建立server socket
14         ServerSocket serverSocket = null;
15         Socket clientSocket = null;
16         try {
17         
18             serverSocket = new ServerSocket(8000);
19             // 【2】等待客戶端的鏈入->阻塞式函數->監聽8000端口,看是否有client鏈入
20             clientSocket = serverSocket.accept();
21             
22             System.out.println(clientSocket.getInetAddress().getHostAddress()+"鏈入!");
23         
24             // 【3】給客戶端主動發信息
25             OutputStream out = clientSocket.getOutputStream();
26             
27             String msg = "hello 兄弟";
28             byte[] buf = msg.getBytes("UTF-8");
29             out.write(buf);
30             clientSocket.shutdownOutput();
31             
32             out.close();
33             
34         
35         } catch (IOException e) {
36             e.printStackTrace();
37         }
38     }
39 }

 

客戶端

 1 package cn.sxt02.net01;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.net.Socket;
 6 
 7 public class Client01 {
 8     public static void main(String[] args) {
 9         System.out.println("客戶端運行...");
10         
11         // 【1】建立客戶端socket
12         Socket socket = null;
13         try {
14             socket = new Socket("192.168.2.56", 8000);
15             
16             // 【2】接收來自服務器的消息
17             InputStream in = socket.getInputStream();
18             byte[] buf = new byte[1024];
19             int len = in.read(buf);
20             
21             String msg = new String(buf, 0, len, "UTF-8");
22             System.out.println(msg);
23             
24         } catch (IOException e) {
25             e.printStackTrace();
26         }
27     }
28 }

雙向通訊

客戶端

 1 import java.io.IOException;
 2 import java.io.InputStream;
 3 import java.io.OutputStream;
 4 import java.io.OutputStreamWriter;
 5 import java.net.ServerSocket;
 6 import java.net.Socket;
 7 
 8 public class ClientSocket {
 9     public static void main(String[] args) {
10         
11         System.out.println("客戶端啓動...");
12         
13         
14         Socket socket=null;
15         try {
16              socket= new Socket("127.0.0.1", 8000);//與服務器創建鏈接,端口號爲8000
17             //接受服務器發送的信息
18              InputStream in=socket.getInputStream();
19              byte[] buf =new byte[1024];
20              int len;         
21              len=in.read(buf);
22              String string = new String(buf, 0, len,"UTF-8");
23              System.out.println(string);
24              socket.shutdownInput();
25              
26             //給服務器發信息
27              OutputStream out = socket.getOutputStream();
28              String string2 = "來了大哥";
29              byte[] buf2 = string2.getBytes("UTF-8");
30              out.write(buf2);
31              socket.shutdownOutput();
32              
33              
34              out.close();
35              in.close();
36              
37              
38             
39         } catch (IOException e) {
40             
41             e.printStackTrace();
42         }
43         
44         
45         
46         
47         
48     }
49 
50 }

服務端

 1 import java.io.IOException;
 2 import java.io.InputStream;
 3 import java.io.OutputStream;
 4 import java.net.ServerSocket;
 5 import java.net.Socket;
 6 
 7 public class Server {
 8     public static void main(String[] args){
 9         System.out.println("服務器啓動...");
10         //[1]建立serversocket
11         ServerSocket serversocket=null;
12         Socket clientsocket =null;
13         try {
14             serversocket = new ServerSocket(8000);
15             //[2]等待客戶端鏈接
16             clientsocket = serversocket.accept();//clientsocket爲鏈接進來的客戶端
17             System.out.println(clientsocket.getInetAddress().getHostAddress()+"連入");
18         } catch (IOException e) {
19         
20             e.printStackTrace();
21         }
22         
23         
24         try {
25             //[3]給客戶端發信息
26             OutputStream out = clientsocket.getOutputStream();
27             String string = "Hello 老弟";
28             byte[] buf = string.getBytes("UTF-8");
29             out.write(buf);
30             clientsocket.shutdownOutput();//告訴客戶端信息已經傳完
31             
32             //[4]接受客戶端發送的信息
33             InputStream in =clientsocket.getInputStream();
34             byte[] buf2 = new byte[1024];
35             int len;
36             len=in.read(buf2);
37             String string2=new String(buf2,0,len,"UTF-8");
38             
39             System.out.println(string2);
40             clientsocket.shutdownInput();
41             
42             
43             in.close();
44             out.close();        
45             
46         } catch (IOException e) {
47         
48             e.printStackTrace();
49         }
50         
51         
52         
53         
54     }
55 
56 }

需求:請上傳張圖片到服務器,並顯示上傳進程。

客戶端

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.IOException;
 4 import java.io.OutputStream;
 5 import java.net.Socket;
 6 /*[1]先將圖片從文件讀取到客戶端程序
【2】將圖片從客戶端程序寫入服務端程序
【3】服務端將圖片寫入目的地文件*/ 7 public class ImgClient { 8 public static void main(String[] args) throws IOException { 9 File file = new File("F:\\javatest\\logo.png"); 10 11 Socket socket=new Socket("127.0.0.1",8888); 12 13 long totallImg = file.length(); 14 long sendLen=0; 15 float progress = 0.0f; 16 17 FileInputStream in=new FileInputStream(file); 18 byte[] buf=new byte[1024]; 19 int len; 20 21 OutputStream out=socket.getOutputStream(); 22 23 24 while ((len=in.read(buf))!=-1) { 25 out.write(buf,0,len); 26 sendLen+=len; 27 progress =sendLen*1.0f/totallImg; 28 System.out.println("上傳進度"+progress); 29 30 31 } 32 33 System.out.println("上傳成功"); 34 socket.shutdownOutput(); 35 in.close(); 36 37 38 39 40 } 41 42 }

服務端

 1 import java.io.File;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 public class ImgServer {
10     public static void main(String[] args) throws IOException {
11         System.out.println("啓動服務器...");
12         ServerSocket serverSocket = new ServerSocket(8888);
13         Socket socketclient=serverSocket.accept();
14         
15         //接收
16         InputStream in=socketclient.getInputStream();
17         byte[] buf=new byte[1024];
18         int len;
19         
20         File file=new File("logo.png");
21         FileOutputStream out=new FileOutputStream(file);    
22         
23         while ((len=in.read(buf))!=-1) {
24               out.write(buf,0,len);
25               
26             
27         }
28         socketclient.shutdownInput();
29         out.close();
30         
31         
32         
33         
34     }
35 
36 }

3. UDP 編程

UDP編程中,若是要完成通訊,通訊雙方必需要建立DatagramSocket,經過DatagramSocket完成通訊。

數據報包用來實現無鏈接包投遞服務。每條報文僅根據該包中包含的信息從一臺機器路由到另外一臺機器

 

UDP步驟:

[1] 建立一個DatagramSocket用於表示發送端,經過send方法發送數據報

[2] 建立一個DatagramSocket用於表示接收端,經過receive方法發送數據報

 

需求:完成一次單向的UDP通訊。

發送端

 1 public static void main(String[] args) {
 2         
 3         // 發送端:主動發送信息
 4         System.out.println("發送端開始發送信息...");
 5         // 【1】建立socket並指定發送數據的端口
 6         DatagramSocket socket = null;
 7         try {
 8             socket = new DatagramSocket(8000);
 9             
10             // 【2】建立數據報包
11             String msg = "hello B";
12             byte[] buf = msg.getBytes("UTF-8");
13             DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 9000);
14             
15             // 【3】發送
16             socket.send(dp);
17             
18             // 【4】關閉
19             socket.close();
20         } catch (SocketException e) {
21             e.printStackTrace();
22         } catch (UnsupportedEncodingException e) {
23             e.printStackTrace();
24         } catch (UnknownHostException e) {
25             e.printStackTrace();
26         } catch (IOException e) {
27             e.printStackTrace();
28         }
29     }

接收端

 1 public static void main(String[] args) {
 2         // 接收端:接收信息
 3         System.out.println("啓動接收端...");
 4         // 【1】建立一個 DatagramSocket
 5         DatagramSocket socket = null;
 6         try {
 7             socket = new DatagramSocket(9000);
 8             // 【2】接收消息
 9             byte[] buf = new byte[1024];
10             DatagramPacket dp = new DatagramPacket(buf, buf.length);
11             System.out.println("等待接收信息...");
12             socket.receive(dp);
13             System.out.println("接收完成...");
14             
15             // 處理接收的信息
16             String msg = new String(buf, 0, dp.getLength(), "UTF-8");
17             System.out.println(msg);
18             
19         } catch (SocketException e) {
20             e.printStackTrace();
21         } catch (IOException e) {
22             e.printStackTrace();
23         }
24     }

 

需求:實現雙向通訊

發送端

 1 public static void main(String[] args) {
 2         
 3         // 發送端:主動發送信息
 4         System.out.println("發送端開始發送信息...");
 5         Scanner sc = new Scanner(System.in);
 6         // 【1】建立socket並指定發送數據的端口
 7         DatagramSocket socket = null;
 8         try {
 9             socket = new DatagramSocket(8000);
10             
11             for(;;) {
12                 System.out.print("A說:");
13                 String msg = sc.nextLine();
14                 byte[] buf = msg.getBytes("UTF-8");
15                 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 9000);
16                 
17                 // 【3】發送
18                 socket.send(dp);
19                 
20                 
21                 // 接收消息
22                 byte[] revBuf = new byte[1024];
23                 DatagramPacket revDp = new DatagramPacket(revBuf,revBuf.length);
24                 socket.receive(revDp);
25                 String revStr = new String(revBuf, 0, revDp.getLength(), "UTF-8");
26                 System.out.println(dp.getAddress().getHostName()+":"+revStr);
27             }
28             
29         } catch (SocketException e) {
30             e.printStackTrace();
31         } catch (UnsupportedEncodingException e) {
32             e.printStackTrace();
33         } catch (UnknownHostException e) {
34             e.printStackTrace();
35         } catch (IOException e) {
36             e.printStackTrace();
37         }finally {
38             // 【4】關閉
39             socket.close();
40         }
41     }

接收端

 1     public static void main(String[] args) {
 2         // 接收端:接收信息
 3         System.out.println("啓動接收端...");
 4         Scanner sc = new Scanner(System.in);
 5         // 【1】建立一個 DatagramSocket
 6         DatagramSocket socket = null;
 7         
 8         try {
 9             socket = new DatagramSocket(9000);
10             
11             for(;;) {
12                 // 接收信息
13                 byte[] buf = new byte[1024];
14                 DatagramPacket dp = new DatagramPacket(buf, buf.length);
15                 socket.receive(dp);
16                 String msg = new String(buf, 0, dp.getLength(), "UTF-8");
17                 System.out.println(dp.getAddress().getHostName()+":"+msg);
18                 
19                 // 發送信息
20                 System.out.println("B說:");
21                 String sendMsg = sc.nextLine();
22                 byte[] sendBuf = sendMsg.getBytes("UTF-8");
23                 DatagramPacket sendDp = new DatagramPacket(sendBuf, 0, sendBuf.length, dp.getAddress(), dp.getPort());
24                 socket.send(sendDp);
25             }
26             
27         } catch (SocketException e) {
28             e.printStackTrace();
29         } catch (IOException e) {
30             e.printStackTrace();
31         }finally {
32             socket.close();
33         }
34     }
相關文章
相關標籤/搜索