Java 網絡編程總結

1、IP地址

IP地址IntAddress:

  • 唯一定位一臺網絡上的計算機
  • 127.0.0.1:本地localhost
  • IP地址的分類

ipV4/ipV6

  • ipV4:127.0.0.1,4個字節組成;0~255,42億~;30億都在北美,亞洲4億;2011年就用完瞭
  • ipV6:128位。8個無符號整數

公網(互聯網)-私網(局域網)

  • ABCD類地址
  • 192.168 .xx.xx,專門給組織內部使用的

域名:方面記憶,免去瞭記錄IP的問題

 1 //測試IP
 2 public class TestInetAddress {
 3     public static void main(String[] args) {
 4         try {
 5             //查詢本機地址
 6             InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
 7             System.out.println(inetAddress);
 8             InetAddress localhost = InetAddress.getByName("localhost");
 9             System.out.println(localhost);
10             InetAddress localHost = InetAddress.getLocalHost();
11             System.out.println(localHost);
12 
13             //查詢網站ip地址
14             InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com");
15             System.out.println(inetAddress1);
16 
17             //常用方法
18             System.out.println(inetAddress1.getHostAddress());//ip
19             System.out.println(inetAddress1.getHostName());//域名,或者自己的名字
20         } catch (UnknownHostException e) {
21             e.printStackTrace();
22         }
23     }
24 }

2、端口

ip相當於省/市/區/街/樓,端口就是門牌號;端口表示計算機上的一個程序的進程

  • 不同的進程有不同的端口號!用來區分軟件!
  • 被規定0~65535
  • TCP,UDP:65535*2;tcp:80;udp:80
  • 端口分類

端口分類:

  • 公有端口0~1023
  • HTTP:80
  • HTTPS:443
  • FTP:21
  • Telent:23

程序註冊端口:1024~49151,分配用戶或者程序

  • Tomcat:8080
  • MySQL:3306
  • Orcal:1521

動態、私有:49152~65535

//CMD
netstat -ano #查看所有的端口
netstat -ano|findstr "5900" #查看指定的端口
tasklist|findstr "8696" #查看指定端口的進程


 1 //端口
 2 public class TestInetSocketAddress {
 3     public static void main(String[] args) {
 4         InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
 5         System.out.println(socketAddress);
 6 
 7         System.out.println(socketAddress.getAddress());
 8         System.out.println(socketAddress.getHostName());//地址
 9         System.out.println(socketAddress.getPort());//端口
10     }
11 }

3、通信協議

協議:約定,共同遵守,都能理解

網絡通信協議:速率,傳輸碼率,代碼結構,傳輸控制….

3.1 TCP/IP協議簇:實際上是一組協議

重要:

  • TCP:用戶傳輸協議
  • UDP:用戶數據報協議

3.2 TCP UDP對比

TCP:打電話

  • 連接,穩定
  • 三次握手,四次揮手
  • 客戶端、服務端
  • 傳輸完成,釋放連接,效率低

UDP:發短信

  • 不連接,不穩定
  • 客戶端、服務端:沒有明確的界限
  • 不管有沒有準備好,都可以發給你

3.3 TCP實現聊天

 1 //服務端
 2 public class TcpServerDemo01 {
 3     public static void main(String[] args) {
 4         ServerSocket serverSocket = null;
 5         Socket accept=null;
 6         InputStream is=null;
 7         ByteArrayOutputStream baos=null;
 8         try {
 9             //1.得有一個地址
10             serverSocket = new ServerSocket(9999);
11 
12             while (true){
13                 //2.等待客戶端連接過來
14                 accept = serverSocket.accept();
15                 //3.讀取客戶端得消息
16                 is = accept.getInputStream();
17 
18                 //管道流
19                 baos = new ByteArrayOutputStream();
20                 byte[] bytes = new byte[1024];
21                 int len;
22                 while ((len=is.read(bytes))!=-1){
23                     baos.write(bytes,0,len);
24                 }
25                 System.out.println(baos.toString());
26             }
27 
28         } catch (IOException e) {
29             e.printStackTrace();
30         }finally {
31             //關閉流
32             try {
33                 baos.close();
34             } catch (IOException e) {
35                 e.printStackTrace();
36             }
37             try {
38                 is.close();
39             } catch (IOException e) {
40                 e.printStackTrace();
41             }
42             try {
43                 accept.close();
44             } catch (IOException e) {
45                 e.printStackTrace();
46             }
47             try {
48                 serverSocket.close();
49             } catch (IOException e) {
50                 e.printStackTrace();
51             }
52 
53         }
54     }
55 }
 1 //客戶端
 2 public class TcpClientDemo01 {
 3     public static void main(String[] args) {
 4         Socket socket=null;
 5         OutputStream os=null;
 6 
 7         try {
 8             //1.要直到服務器得地址
 9             InetAddress serverIP= InetAddress.getByName("127.0.0.1");
10             int port=9999;
11             //2.創建一個socker連接
12             try {
13                 socket = new Socket(serverIP,port);
14                 //3.發送消息 IO流
15                 os = socket.getOutputStream();
16                 os.write("Hello".getBytes());
17             } catch (IOException e) {
18                 e.printStackTrace();
19             }
20 
21 
22         } catch (UnknownHostException e) {
23             e.printStackTrace();
24         }finally {
25             try {
26                 os.close();
27             } catch (IOException e) {
28                 e.printStackTrace();
29             }
30             try {
31                 socket.close();
32             } catch (IOException e) {
33                 e.printStackTrace();
34             }
35         }
36     }
37 }

3.4 TCP文件上傳

 1 //服務端
 2 public class TcpServerDemo02 {
 3     public static void main(String[] args) throws Exception{
 4         //1.創建服務
 5         ServerSocket serverSocket = new ServerSocket(9000);
 6         //2.監聽客戶端得連接
 7         Socket accept = serverSocket.accept();//阻塞式監聽,會一直等待客戶端得連接
 8         //3.獲取輸入流
 9         InputStream is = accept.getInputStream();
10 
11         //4.文件輸出
12         FileOutputStream fos = new FileOutputStream("receive.jpg");
13         byte[] by = new byte[1024];
14         int len;
15         while ((len=is.read(by))!=-1){
16             fos.write(by,0,len);
17         }
18 
19         //通知客戶端我接收完畢瞭
20         OutputStream os = accept.getOutputStream();
21         os.write("接收完畢".getBytes());
22 
23         os.close();
24         fos.close();
25         is.close();
26         accept.close();
27         serverSocket.close();
28     }
29 }
 1 //客戶端
 2 public class TcpClientDemo02 {
 3     public static void main(String[] args) throws Exception{
 4         //1.創建一個socket連接
 5         Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
 6         //2.創建一個輸出流
 7         OutputStream os = socket.getOutputStream();
 8 
 9         //3.讀取文件
10         FileInputStream fis = new FileInputStream("D:\\WorkSpace\\JavaSE\\基礎語法\\111.png");
11         //4.寫出文件
12         byte[] by = new byte[1024];
13         int len;
14         while ((len=fis.read(by))!=-1){
15             os.write(by,0,len);
16         }
17 
18         //通知服務器,我已經傳輸結束瞭
19         socket.shutdownOutput();
20 
21         //確認服務器接收完畢,才能斷開連接
22         InputStream is = socket.getInputStream();
23         ByteArrayOutputStream baos = new ByteArrayOutputStream();
24 
25         byte[] bytes = new byte[1024];
26         int leng;
27         while ((leng=is.read(bytes))!=-1){
28             baos.write(bytes,0,leng);
29         }
30         System.out.println(baos.toString());
31 
32         baos.close();
33         is.close();
34         os.close();
35         fis.close();
36         socket.close();
37     }
38 }

3.5 UDP消息發送

 1 //發送方
 2 public class UdpClientDemo01 {
 3     public static void main(String[] args) throws Exception{
 4         //1.建立一個Socket
 5         DatagramSocket datagramSocket = new DatagramSocket();
 6 
 7         //2.建個包
 8         String msg="你好啊,服務器!";
 9         InetAddress localhost = InetAddress.getByName("localhost");
10         int port = 9090;
11 
12         //數據、數據的長度起始、要發給誰
13         DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
14 
15         //發送包
16         datagramSocket.send(datagramPacket);
17 
18         //4.關閉流
19         datagramSocket.close();
20     }
21 }
 1 //接收方
 2 public class UdpServerDemo01 {
 3     public static void main(String[] args) throws Exception{
 4         //開放端口
 5         DatagramSocket datagramSocket = new DatagramSocket(9090);
 6         //接收數據
 7         byte[] bytes = new byte[1024];
 8         DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
 9 
10         datagramSocket.receive(datagramPacket);//阻塞接收
11 
12         System.out.println(datagramPacket.getAddress());
13         System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
14     }
15 }

3.6 UDP聊天實現

 1 //發送方
 2 public class UdpSenderDemo01 {
 3     public static void main(String[] args) throws Exception{
 4 
 5         DatagramSocket datagramSocket = new DatagramSocket(8888);
 6 
 7         //準備數據:控制臺讀取System.in
 8         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 9 
10         while (true){
11             String data=reader.readLine();
12             byte[] bytes = data.getBytes();
13             DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress("localhost",6666));
14             datagramSocket.send(datagramPacket);
15             if(bytes.equals("byebye")){
16                 break;
17             }
18         }
19         datagramSocket.close();
20     }
21 }
 1 //接收方
 2 public class UdpReceiveDemo01 {
 3     public static void main(String[] args) throws Exception{
 4         DatagramSocket datagramSocket = new DatagramSocket(6666);
 5 
 6         while (true){
 7             //準備接收包裹
 8             byte[] bytes = new byte[1024];
 9             DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
10 
11             //斷開連接 byebye
12             byte[] data = datagramPacket.getData();
13             String string = new String(data, 0, data.length);
14             System.out.println(string);
15             if(string.equals("byebye")){
16                 break;
17             }
18         }
19 
20         datagramSocket.close();
21 
22     }
23 }

到此這篇關於Java 網絡編程總結的文章就介紹到這瞭,更多相關Java 網絡編程內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: