世界速訊:狂神說 網絡編程實戰講解

2022-12-13 11:16:58 來源:51CTO博客

1.1、概述

計算機網絡:

計算機網絡是指將地理位置不同的具有獨立功能的多臺過算機及其外部設備,通過通信線路連接起來,在網絡操作系統,網絡管理軟件及網絡通信協議的管理和協調下,實現資源共享和信息傳遞的計算機系統。

網絡編程的目的:

無線電臺...傳播交流信息,數據交換。通信


(資料圖片僅供參考)

想要達到這個效果需要什么:

1.如何準確的定位網絡.上的一臺主機192.168.16.124: 端口,定位到這個計算機上的某個資源

2.找到了這個主機,如何傳輸數據呢?

javaweb:網頁編程 B/S網絡編程: TCP/IP C/S

1.2、網絡通信的要素

如何實現網絡的通信?

通信雙方地址:
ip端口號192.168.16,124:5900
規則:網絡通信的協議

http, ftp,smtp,tcp, udp。。。

小結:

1.網絡編程中有兩個主要的問題

如何準確的定位到網絡.上的一臺或者多臺主機找到主機之后如何進行通信2.網絡編程中的要素IP和端口號ip網絡通信寫協議tcp udp3.萬物皆對象

1.3、IP

ABCD類地址

1.4、端口

端口表示計算機上的一個程序的進程

不同的進程有不同的端口號!用來區分軟件!被規定0!65535TCP,UDP:65535*2 單個協議下 端口不能沖突端口分類公有端口0~1023HTTP:80HTTPS:443FTP:21Telent:23程序注冊端口:1014~49151,分配給用戶或者程序Tomcat:8080MySQL:3306Oracle:1521動態、私有:46152~65535
netstat -ano  #查看所有端口netstat -ano|findstr "5900"  #查看指定端口tasklist|findstr "8696" #查看指定端口的進程
## 1.5、通信協議網絡通信協議:速率,傳輸碼率,代碼結構,傳輸控制...問題:非常的復雜?大事化小:分層!TCP/IP協議簇:實際上是一組協議**重要**:****●TCP :用戶傳輸協議●UDP:用戶數據報協議出名的協議:****●TCP:●IP:網絡互連協議#### TCP UDP 對比TCP:打電話- 連接。穩定- 三次握手,四次揮手  1. ```     A:你瞅啥?     B:瞅你咋地?     A:干一場!               A:我要斷開了     B:你真的要走了么     A:你真的真的要走了么     A:我真的要走了
客戶端,服務端傳輸完成,釋放連接,效率低

UDP 發短信

不連接,不穩定客戶端、服務端:沒有明顯的界限不管有沒有準備好,都可以發給你導彈DDOS:洪水攻擊(飽和攻擊)

1.6、TCP

客戶端

連接服務器發送消息
package com.network.lesson02;import java.io.IOException;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;public class TcpCilentDemo01 {    public static void main(String[] args) {        //1.要知道服務器的地址 端口號        Socket socket=null;        OutputStream os=null;        try {            InetAddress byName = InetAddress.getByName("127.0.0.1");            int port=9999;            //2.創建一個socket連接            socket = new Socket(byName,port);            //3.發送IO消息流            os = socket.getOutputStream();            os.write("大家一起學Java".getBytes());        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (os!=null){                try {                    os.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (socket!=null){                try {                    socket.close ();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

服務器

建立服務器的端口ServerSocket等待用戶的連接 accpet接收用的消息
package com.network.lesson02;import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TcpServerDemo01 {    public static void main(String[] args) {        //1.有一個地址        ServerSocket serverSocket =null;        Socket socket=null;        InputStream is=null;        ByteArrayOutputStream baos=null;        try {             serverSocket = new ServerSocket(9999);            //2.等待客戶端連接過來            socket = serverSocket.accept();            //3.讀取客戶端的消息            is = socket.getInputStream();            /*bug寫法            byte[] buffer = new byte[1024];            int len;            while ((len=is.read(buffer))!=-1){                String msg = new String(buffer, 0, len);                System.out.println(msg);             */            //管道流            baos = new ByteArrayOutputStream();            int len;            byte[] buffer = new byte[1024];            while ((len= is.read(buffer))!=-1){                baos.write(buffer,0,len);            }            System.out.println(baos.toString());            //先開后關        } catch (IOException e) {            e.printStackTrace();        }finally {            //關閉資源            if (baos!=null){                try {                    baos.close();                } catch (IOException e) {                    e.printStackTrace();                }                if (is!=null){                    try {                        is.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                if (socket!=null){                    try {                        socket.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                if (serverSocket!=null){                    try {                        serverSocket.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }    }}
文件上傳

服務器端

package com.network.lesson02;import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TcpServerDemo02 {    public static void main(String[] args) throws Exception {//        1.創建服務        ServerSocket serverSocket = new ServerSocket(9000);//        Socket socket = new Socket();//2.監聽客戶端鏈接        Socket socket = serverSocket.accept();//阻塞式監聽,會一直等待客戶端輸入//        3.獲得輸入流        InputStream is = socket.getInputStream();//        4.文件輸出        FileOutputStream fos = new FileOutputStream(new File("hhhh.jpg"));        byte[] buffer = new byte[1024];        int len;        while ((len=is.read(buffer))!=-1){            is.read(buffer,0,len);        }//通知客戶端接收完畢        OutputStream os = socket.getOutputStream();        os.write("我接收完畢了,你可以斷開了".getBytes());//        5.關閉資源        fos.close();        is.close();        socket.close();        serverSocket.close();    }}

客戶端

package com.network.lesson02;import java.io.*;import java.net.InetAddress;import java.net.Socket;public class TcpCilentDemo02 {    public static void main(String[] args) throws Exception {        //1.創建一個socket連接        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);//        2.創建一個輸出流        OutputStream os = socket.getOutputStream();//        3.讀取文件     把文件變成流   再把流輸出        FileInputStream fis = new FileInputStream(new File("1.jpg"));//        4.寫出文件        byte[] buffer = new byte[1024];//緩沖區 ·1        int len;        while ((len= fis.read(buffer))!=-1){            os.write(buffer,0,len);        }        //通知服務器 輸出完了        socket.shutdownOutput();        //確定服務器接收完畢才能斷開鏈接        InputStream inputStream = socket.getInputStream();        ByteArrayOutputStream baos = new ByteArrayOutputStream();        byte[] buffer2 = new byte[1024];        int len2;        while ((len2=inputStream.read(buffer2))!=-1){            baos.write(buffer2,0,len2);        }        System.out.println(baos.toString());//        確定服務//        5.關閉資源        baos.close();        fis.close();        os.close();        socket.close();    }}

Tomcat

服務端

自定義Tomcat服務器

客戶端

自定義 C瀏覽器 B

1.7、UDP

發消息:不用連接,需要知道對方的地址!

發送消息
package com.network.lesson03;import java.net.*;//不需要連接服務器public class UdpCelientDemo01 {    public static void main(String[] args) throws Exception {        //1.建立一個Socket        DatagramSocket socket = new DatagramSocket();        //2.建個包        String msg="你好啊,服務器!!";        //發給誰        InetAddress localhost = InetAddress.getByName("localhost");        int port = 9090;        //數據,數據的長度起始,要發送給誰        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);        socket.send(packet);        //關閉        socket.close();    }}
接收端
package com.network.lesson03;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpServerDemo01 {    //還是要等待客戶端的連接    public static void main(String[] args) throws Exception {        //開放端口        DatagramSocket socket = new DatagramSocket(9090);        //接收數據        byte[] buffer = new byte[1024];        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);        socket.receive(packet);//阻塞接受        System.out.println(packet.getAddress().getHostAddress());        System.out.println(new String(packet.getData(),0,packet.getLength()));        socket.close();    }}

咨詢

循環發送消息
package com.network.chat;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.*;public class UdpSender01 {    public static void main(String[] args) throws Exception {        DatagramSocket socket = new DatagramSocket(8888);        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));        while (true){            String data = reader.readLine();            byte[] datas = data.getBytes();            String sendData=new String(datas,0,datas.length);            if (sendData.equals("bye")){                break;            }            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));            socket.send(packet);        }        socket.close();    }}
循環接收消息
package com.network.chat;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpReceive01 {    public static void main(String[] args) throws Exception {        DatagramSocket socket = new DatagramSocket(6666);        while (true){            byte[] container = new byte[1024];            DatagramPacket packet = new DatagramPacket(container,0,container.length);            socket.receive(packet);//阻塞式接受包裹            byte[] data = packet.getData();            String receiveData=new String(data,0,data.length);            System.out.println(receiveData);            if (receiveData.equals("bye")){                break;            }        }        socket.close();    }}

1.8、URL

統一資源定位符

DNS域名解析 ip 域名

協議://IP地址:端口/項目名/資源

爬取

package com.network.lesson04;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class URLDown {    public static void main(String[] args) throws IOException {//        https://m701.music.126.net/20220215002141/95215abe6a0cacbbac7f4386691694cd/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/11624482968/5b8b/9912/7c40/3877aa1c480cedeb274dae1b816efbb6.m4a//        漠河舞廳        URL url = new URL("https://m701.music.126.net/20220215002141/95215abe6a0cacbbac7f4386691694cd/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/11624482968/5b8b/9912/7c40/3877aa1c480cedeb274dae1b816efbb6.m4a");        System.out.println(url.getHost());        System.out.println(url.getPort());        System.out.println(url.getUserInfo());        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();        InputStream inputStream = urlConnection.getInputStream();        FileOutputStream fos = new FileOutputStream("親愛的漠河舞廳.m4a");        byte[] buffer = new byte[1024];        int len;        while ((len=inputStream.read(buffer))!=-1){            fos.write(buffer,0,len);        }        fos.close();        inputStream.close();        urlConnection.disconnect();    }}

標簽: 網絡通信 接收完畢 發送消息

上一篇:消息!Zabbix 6 系列學習 05:Zabbix Appliance
下一篇:Mybatis源碼解析之執行SQL語句