• java基础15


    一、网络编程

    相关概念

    网络

    在这里插入图片描述

    网络通信

    在这里插入图片描述

    ip地址

    在这里插入图片描述

    ipv4地址分类

    A类一个字节的网络号,3个字节的主机号
    B类两个字节的网络号,2个字节的主机号
    C类三个字节的网络号,1个字节的主机号
    D类地址:D类IP地址不分网络号和主机号,它固定以“110”开头
    E类地址:E类地址不分网络号和主机号,它固定以“11110”开头
    在这里插入图片描述

    域名和端口号

    在这里插入图片描述

    ip找主机,端口找服务
    在这里插入图片描述

    网络协议

    数据在网络编程中的组织形式就叫协议

    在这里插入图片描述
    在这里插入图片描述

    TCP和UDP(传输层)

    在这里插入图片描述

    举例
    在这里插入图片描述

    InetAddress类

    在这里插入图片描述
    在这里插入图片描述

    public class API_ {
        public static void main(String[] args) throws UnknownHostException {
    
            //获取本机InetAddress对象
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);
    
            //根据指定的主机名获取InetAddress对象
            InetAddress host1 = InetAddress.getByName("MaybEdeMacBook-Pro.local");
            System.out.println(host1);
    
            //根据域名返回InetAddress对象
            InetAddress host2 = InetAddress.getByName("www.baidu.com");
            System.out.println(host2);
    
            //通过InetAddress对象获取对应的地址
            String hostAddress = host2.getHostAddress();
            System.out.println(hostAddress);
    
            //通过InetAddress对象获取对应的主机名或者域名
            String hostName = host2.getHostName();
            System.out.println(hostName);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    Socket套接字

    就是数据通道两端读写数据的东西
    在这里插入图片描述
    在这里插入图片描述

    TCP网络通信编程

    记得关闭Socket
    在这里插入图片描述

    案例1:

    在这里插入图片描述
    在这里插入图片描述

    SocketTCP01Server.java

    public class SocketTCP01Server {
        public static void main(String[] args) throws IOException {
            //思路:
            //1.在本机的9999端口监听,等待连接
            //ServerSocket可以对应多个socket
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务端在9999端口等待连接...");
            //2.当没有客户端连接9999端口的时候,程序会阻塞,等待连接,如果有客户端连接,则会返回一个Socket对象
            Socket socket = serverSocket.accept();
            System.out.println("服务端socket=" + socket.getClass());
            //3.通过socket.getInputStream()读取
            InputStream inputStream = socket.getInputStream();
            //4.IO读取
            byte[] bytes = new byte[64];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
            //4.关闭流和socket
            inputStream.close();
            socket.close();
            serverSocket.close();
            System.out.println("服务端退出了");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    SocketTCP01Client.java

    public class SocketTCP01Client {
        public static void main(String[] args) throws UnknownHostException, IOException {
            //思路:
            //1.连接服务器(ip,端口),如果连接成功但会socket对象
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            System.out.println("客户端socket返回" + socket.getClass());
            //2.连接上后,生成Socket,通过socket.getOutputStream得到和socket对象关联的输出流对象
            OutputStream outputStream = socket.getOutputStream();
            //3.通过输出流,写入数据到数据通道
            outputStream.write("hello,server".getBytes());
            //4.关闭流对象和socket
            outputStream.close();
            socket.close();
            System.out.println("客户端退出了");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    案例2:

    注意: 写入结束时要设置写入结束标记 socket.shutdownOutput();
    否则会出现服务端和客户端都在等待的情况

    在这里插入图片描述
    SocketTCP02Server.java

    public class SocketTCP02Server {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("server端在等待连接");
            Socket socket = serverSocket.accept();
            System.out.println("server的socket=" + socket.getClass());
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello,client".getBytes());
    
    
            //设置写入结束标记
            socket.shutdownOutput();
    
            
            outputStream.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    SocketTCP02Client.java

    public class SocketTCP02Client {
        public static void main(String[] args) throws UnknownHostException, IOException {
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            System.out.println("client端的socket=" + socket.getClass());
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello,server".getBytes());
    
            //设置写入结束标记
            socket.shutdownOutput();
    
            
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
            outputStream.close();
            inputStream.close();
            socket.close();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    案例3:

    在这里插入图片描述
    在这里插入图片描述
    SocketTCP03Server.java

    public class SocketTCP03Server {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("server=" + serverSocket.getClass());
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();//这里不能用while
            System.out.println(s);
    
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("hello,client");
            bufferedWriter.newLine();
            bufferedWriter.flush();
    //        bufferedWriter.close();
            bufferedReader.close();
            socket.close();
            serverSocket.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    SocketTCP03Client.java

    public class SocketTCP03Client {
        public static void main(String[] args) throws UnknownHostException, IOException {
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            System.out.println("Client=" + socket.getClass());
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("hello,server");
            //也可以通过newLine设置写入结束标记,但是另一边读的时候必须使用readLine,读到newLine结束
            bufferedWriter.newLine();
            bufferedWriter.flush();//使用字符流需要手动刷新,否则数据不会写入通道
    //        bufferedWriter.close();//缓存区没满,直接使用close方法不会自动的朝目标文件进行读或写
    
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s;
            while ((s = bufferedReader.readLine()) != null) {
                System.out.println(s);
            }
            bufferedReader.close();
            bufferedWriter.close();
            socket.close();
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    案例4:

    在这里插入图片描述
    难点在于:socket的相关方法可以返回OutputStream和InputStream类型,但是本地文件是用FileInputStream和FileOutputStream类型的。
    所以关键在于,把FileInputStream本地读到的数据及时通过BufferedOutputStream写入

    netstat指令

    0.0.0.0代表本机,冒号后面的是端口号
    外部地址是指有谁连到了本机上(在服务器上,本地是服务端,外部地址是客户端)
    在这里插入图片描述

    TCP不为人知的秘密

    客户端和服务端的通信也是通过端口来实现的,不过客户端的端口是TCP/IP随机分配的,通信结束后端口就回收了。

    在客户端能看到服务端的地址,服务端可以看到客户端的地址。
    在这里插入图片描述
    在这里插入图片描述

    UDP网络通信编程

    在这里插入图片描述

    基本流程

    在这里插入图片描述

    UDP网络编程原理示意图

    在这里插入图片描述

    应用案例

    在这里插入图片描述

    示意图

    在这里插入图片描述

    代码

    UDPReceiverA.java

    public class UDPReceiverA {
        public static void main(String[] args) throws UnknownHostException, IOException {
            //1.创建一个DatagramSocket对象,准备在9999接收数据
            DatagramSocket datagramSocket = new DatagramSocket(9999);
            //2.构建一个DatagramPacket对象,准备接收数据
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            //3.调用 接收方法接收,将通过网络传输的DatagramPacket对象,填充到空的datagramPacket中去
            //当有数据报发送到9999端口时,datagramPacket就会接收,如果没有数据报发送就会阻塞等待
            System.out.println("接收端A等待接收数据");
            datagramSocket.receive(datagramPacket);
            //4.可以把datagramPacket进行拆包,取出数据并显示
            int len = datagramPacket.getLength();//实际接收到的数据字节长度
            byte[] data = datagramPacket.getData();//接收到的数据
            String s = new String(data, 0, len);
            System.out.println(s);
    
            //5 回复发送端"好的,明天见"
            bytes = "好的,明天见".getBytes();
            //5.1 datagramPacket中封装要发送的内容
            datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9998);
            //5.2 datagramSocket发送datagramPacket
            datagramSocket.send(datagramPacket);
            System.out.println("回复完毕");
    
            //6.关闭资源
            datagramSocket.close();
            System.out.println("A端退出了");
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    UDPSenderB.java

    public class UDPSenderB {
        public static void main(String[] args) throws IOException {
            //1.发送端也是可以接收数据的,但是9999端口被用了,所以设个9998端口
            DatagramSocket socket = new DatagramSocket(9998);
            //2.将需要发送的数据封装到DatagramPacket对象
            byte[] bytes = "hello,明天吃火锅".getBytes();
            //3.说明封装的DatagramPacket对象   需要的参数包括 data内容字节数组,data.length,主机地址(ip),端口
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("172.16.103.35"), 9999);
            socket.send(packet);
    
            //4.接收A端发送过来的消息
            //4.1packet封装收到的消息
            byte[] data = new byte[1024];
            packet = new DatagramPacket(data, data.length);
            socket.receive(packet);
            //4.2packet拆包
            int len = packet.getLength();
            bytes = packet.getData();
            System.out.println(new String(bytes, 0, len));
            //5.关闭资源
            socket.close();
            System.out.println("B端退出了");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    homework

    1

    在这里插入图片描述
    Homework01Server.java

    public class Homework01Server {
        static String s;
        static boolean flag = true;
    
        public static void main(String[] args) throws IOException {
            //准备接收工作
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务端等待中");
            Socket socket = serverSocket.accept();
            System.out.println("服务器收到了");
            //读
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //写
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
    
            while (flag) {
                answer(bufferedWriter, bufferedReader);
            }
    
            bufferedWriter.close();
            bufferedReader.close();
            socket.close();
            serverSocket.close();
        }
    
        public static void whatYouSay(BufferedWriter bufferedWriter) {
            try {
                bufferedWriter.write("你说啥呢");
                bufferedWriter.newLine();
                bufferedWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static void answer(BufferedWriter bufferedWriter, BufferedReader bufferedReader) throws IOException {
            s = bufferedReader.readLine();
            if (s.equals("name")) {
                System.out.println(s);
    
                //回复名字
                bufferedWriter.write("nova");
                bufferedWriter.newLine();
                bufferedWriter.flush();
    
            } else if (s.equals("hobby")) {
                System.out.println(s);
    
                //回复hobby
                bufferedWriter.write("边写java程序");
                bufferedWriter.newLine();
                bufferedWriter.flush();
            } else if (s.equals("no")) {
                flag = false;
            } else {
                whatYouSay(bufferedWriter);
            }
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    Homework01Client.java

    public class Homework01Client {
        static String s;
        static boolean flag = true;
    
        public static void main(String[] args) throws IOException {
            //准备发送工作
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            //写
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            //读
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            Scanner scanner = new Scanner(System.in);
    
            //问
            while (flag) {
                ask(bufferedWriter, bufferedReader, scanner);
            }
    
            bufferedReader.close();
            bufferedWriter.close();
            socket.close();
        }
    
        public static void ask(BufferedWriter bufferedWriter, BufferedReader bufferedReader, Scanner scanner) throws IOException {
            System.out.println("请输入你想问的问题:(no就退出)");
            String question = scanner.next();
            if (question.equals("no")) {
                flag = false;
            }
    
            //这边弄混了newLine()和flush()顺序导致写入失败
    
            bufferedWriter.write(question);
            bufferedWriter.newLine();
            bufferedWriter.flush();
            s = bufferedReader.readLine();
            System.out.println(s);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    2

    在这里插入图片描述
    Homework02ReceiverA.java

    public class Homework02ReceiverA {
        public static void main(String[] args) throws IOException {
            DatagramSocket socket = new DatagramSocket(8888);
            //收/答
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            socket.receive(packet);
            byte[] data = packet.getData();
            //注意,这边的length如果不是packet.getLength会出现乱码
    //        String s = new String(data, 0, data.length);
            String s = new String(data, 0, packet.getLength());
            System.out.println(s);
    
            //回
    
            bytes = s.equals("四大名著是哪些") ? "四大名著是<<红楼梦>>....".getBytes() : "what?".getBytes();
            packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 8889);
            socket.send(packet);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    Homework02SenderB.java

    public class Homework02SenderB {
        public static void main(String[] args) throws IOException {
            DatagramSocket socket = new DatagramSocket(8889);
            //问/发
            byte[] bytes = "四大名著是哪些?".getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 8888);
            socket.send(packet);
    
            //收
            bytes = new byte[1024];
            packet = new DatagramPacket(bytes, bytes.length);
            socket.receive(packet);
            bytes = packet.getData();
    //        System.out.println(new String(bytes, 0, bytes.length));
            System.out.println(new String(bytes, 0, packet.getLength()));
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3.TCP文件下载

    在这里插入图片描述
    Homework03Client.java

    public class Homework03Client {
        public static void main(String[] args) throws IOException {
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入音乐名:");
            String s = scanner.next();
    
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(s);
            bufferedWriter.newLine();
            bufferedWriter.flush();
    
    
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            String path = new File("./src/" + s).exists() ? ("./src/music/" + s) : "./src/music/真的爱你.mflac";
            receive(path, bufferedInputStream);
    
            bufferedInputStream.close();
            bufferedWriter.close();
            socket.close();
    
        }
    
        public static void receive(String path, BufferedInputStream bufferedInputStream) throws IOException {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            byte[] bytes = new byte[1024];
            while (bufferedInputStream.read(bytes) != -1) {
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
            }
            fileOutputStream.close();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    Homework03Server.java

    public class Homework03Server {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = new ServerSocket(9999);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
    
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();
            String path = "./src/" + s;
            String pathDefault = "./src/真的爱你.mflac";
            File file = new File(path);
            if (file.exists()) {
                sendMusic(path, bufferedOutputStream);
            } else {
                sendMusic(pathDefault, bufferedOutputStream);
            }
            bufferedOutputStream.close();
            bufferedReader.close();
            socket.close();
            serverSocket.close();
        }
    
        public static void sendMusic(String path, BufferedOutputStream bufferedOutputStream) throws IOException {
            FileInputStream fileInputStream = new FileInputStream(path);
            byte[] bytes = new byte[1024];
            while (fileInputStream.read(bytes) != -1) {
                bufferedOutputStream.write(bytes);
                bufferedOutputStream.flush();
            }
            fileInputStream.close();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    java基础之Map集合
    web3 入门记录
    Hadoop总结
    FreeMarkerViewResolver类简介说明
    【Redis】五大基本数据类型操作大全
    LeetCode 643. Maximum Average Subarray I
    十、rem适配方案
    聊一聊,今年参加软考高级的一些总结
    双连通与网络可靠性
    编译Redis时报错: jemalloc/jemalloc.h: No such file or directory
  • 原文地址:https://blog.csdn.net/weixin_43903745/article/details/126286699