• 网络编程基础


    网络编程

    1.网络的相关概念

    1.1 网络通信

    image-20220213183213563

    1.2 网络

    image-20220213183226249

    1.3 ip地址

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yEsSYMqB-1658245480040)(https://b3logfile.com/file/2022/02/solo-fetchupload-4518088803244381275-c47d8c8e.png)]

    1.4 ipv4地址分类

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zpMxEbKQ-1658245480040)(https://b3logfile.com/file/2022/02/solo-fetchupload-2671560972323300665-83b937e4.png)]

    image-20220213211126809

    1.5 域名

    image-20220213211153007

    1.6 网络通信协议

    image-20220213211216239

    image-20220213211320906

    image-20220213213310939

    1.7 TCP和UDP

    image-20220213213443175

    TCP

    三次握手,确认连接时可靠的,效率较低

    image-20220213215738259

    UDP

    tom说完就走,效率较高,但kim不一定听到了,稳定性较差

    image-20220213215948896

    2. InetAddress 类

    2.1相关方法

    image-20220213221349139

    public class API_ {
        public static void main(String[] args) throws UnknownHostException {
    
            //1. 获取本机的InetAddress 对象
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);//DESKTOP-S4MP84S/192.168.12.1
    
            //2. 根据指定主机名 获取 InetAddress对象
            InetAddress host1 = InetAddress.getByName("DESKTOP-S4MP84S");
            System.out.println("host1=" + host1);//DESKTOP-S4MP84S/192.168.12.1
    
            //3. 根据域名返回 InetAddress对象, 比如 www.baidu.com 对应
            InetAddress host2 = InetAddress.getByName("www.baidu.com");
            System.out.println("host2=" + host2);//www.baidu.com / 110.242.68.4
    
            //4. 通过 InetAddress 对象,获取对应的地址
            String hostAddress = host2.getHostAddress();//IP 110.242.68.4
            System.out.println("host2 对应的ip = " + hostAddress);//110.242.68.4
    
            //5. 通过 InetAddress 对象,获取对应的主机名/或者的域名
            String hostName = host2.getHostName();
            System.out.println("host2对应的主机名/域名=" + hostName); // www.baidu.com
    
        }
    }
    
    • 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

    应用

    image-20220213221359118

    3.Socket

    3.1基本介绍

    image-20220213221637518

    示意图
    image-20220213222149905

    4.TCP网络通信编程

    4.1基本介绍

    image-20220213222724392

    image-20220213222728946

    4.2应用案例 1(使用字节流)

    image-20220214221343866

    服务端

    public class SocketTCP01Server {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 在本机 的9999端口监听, 等待连接
            //   细节: 要求在本机没有其它服务在监听9999
            //   细节:这个 ServerSocket 可以通过 accept() 返回多个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[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = inputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));//根据读取到的实际长度,显示内容.
            }
            //5.关闭流和socket
            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
    • 28
    • 29

    客户端

    public class SocketTCP01Client {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 连接服务端 (ip , 端口)
            //解读: 连接本机的 9999端口, 如果连接成功,返回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
    • 18

    4.3 应用案例2(使用字节流)

    image-20220214221631623

    服务端

    public class SocketServer02 {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务器端建立连接。。。。。。。");
            Socket socket = serverSocket.accept();
    
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = 0;
            while ((read = inputStream.read(bytes))!=-1){
                System.out.println(new String(bytes,0,read));
            }
      
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("哈哈哈".getBytes());
            outputStream.close();
            inputStream.close();
            socket.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

    客户端

    public class SocketClient02 {
        public static void main(String[] args) throws IOException {
            Socket socket = new Socket(InetAddress.getLocalHost(),9999);
            System.out.println("客户端建立连接..........");
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("悟空~\n哈哈哈".getBytes());
    
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
    
            int read = 0;
            while ((read = inputStream.read(bytes))!=-1){
                System.out.println(new String(bytes,0,read));
            }
            inputStream.close();
            socket.close();
            outputStream.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

    这里程序看似没什么问题,但是运行之后会发现客户端拿不到服务器端的消息,而且服务器端和客户端都无法退出

    image-20220214224105253

    分析

    A可以看作客户端,B看作服务器端

    客户端在读取服务器端内容是并不知道服务器端是否还有内容,进而导致客户端和服务器端都卡住了~

    解决办法

    在服务器端、客户端写入数据之后,设置写入结束标记 socket.shutdownOutput();

    image-20220214223340305

    服务端

    public class SocketTCP02Server {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 在本机 的9999端口监听, 等待连接
            //   细节: 要求在本机没有其它服务在监听9999
            //   细节:这个 ServerSocket 可以通过 accept() 返回多个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[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = inputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));//根据读取到的实际长度,显示内容.
            }
            //5. 获取socket相关联的输出流
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello, client".getBytes());
            //   设置结束标记
            socket.shutdownOutput();
    
            //6.关闭流和socket
            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
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    客户端

    public class SocketTCP02Client {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 连接服务端 (ip , 端口)
            //解读: 连接本机的 9999端口, 如果连接成功,返回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());
            //   设置结束标记
            socket.shutdownOutput();
    
            //4. 获取和socket关联的输入流. 读取数据(字节),并显示
            InputStream inputStream = socket.getInputStream();
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = inputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));
            }
    
            //5. 关闭流对象和socket, 必须关闭
            inputStream.close();
            outputStream.close();
            socket.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
    • 27
    • 28
    • 29
    • 30

    4.3应用案例3(使用字符流)

    image-20220214230852405

    image-20220214225254780

    服务端

    public class SocketTCP03Server {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 在本机 的9999端口监听, 等待连接
            //   细节: 要求在本机没有其它服务在监听9999
            //   细节:这个 ServerSocket 可以通过 accept() 返回多个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读取, 使用字符流, 老师使用 InputStreamReader 将 inputStream 转成字符流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();
            System.out.println(s);//输出
    
            //5. 获取socket相关联的输出流
            OutputStream outputStream = socket.getOutputStream();
           //    使用字符输出流的方式回复信息
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("hello client 字符流");
            bufferedWriter.newLine();// 插入一个换行符,表示回复内容的结束 或者使用socket.shutdownOutput();   
            bufferedWriter.flush();//注意需要手动的flush
    
    
            //6.关闭流和socket
            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
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    客户端

    public class SocketTCP03Client {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 连接服务端 (ip , 端口)
            //解读: 连接本机的 9999端口, 如果连接成功,返回Socket对象
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            System.out.println("客户端 socket返回=" + socket.getClass());
            //2. 连接上后,生成Socket, 通过socket.getOutputStream()
            //   得到 和 socket对象关联的输出流对象
            OutputStream outputStream = socket.getOutputStream();
            //3. 通过输出流,写入数据到 数据通道, 使用字符流
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write("hello, server 字符流");
            bufferedWriter.newLine();//插入一个换行符,表示写入的内容结束, 注意,要求对方使用readLine()!!!! 或者使用socket.shutdownOutput();   
            bufferedWriter.flush();// 如果使用的字符流,需要手动刷新,否则数据不会写入数据通道
    
    
            //4. 获取和socket关联的输入流. 读取数据(字符),并显示
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();
            System.out.println(s);
    
            //5. 关闭流对象和socket, 必须关闭
            bufferedReader.close();//关闭外层流
            bufferedWriter.close();
            socket.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
    • 27
    • 28
    • 29
    • 30

    4.4 应用案例4(TCP文件下载)

    image-20220215212229105

    image-20220215212110843

    这个需求看似简单,但是在编写过程中我错了很多次,需要注意点一些细节。

    1.客户端首先需要获取磁盘上的文件并写入到socket.getOutputStream

    2.服务端接受文件需要将接收到的流转换成功二进制数组并写入文件中

    3.在写入数据时需要设置写入数据的结束标记 socket.shutdownOutput();

    工具类

    public class StreamUtils {
    	/**
    	 * 功能:将输入流转换成byte[]
    	 * @param is
    	 * @return
    	 * @throws Exception
    	 */
    	public static byte[] streamToByteArray(InputStream is) throws Exception{
    		ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出流对象
    		byte[] b = new byte[1024];
    		int len;
    		while((len=is.read(b))!=-1){
    			bos.write(b, 0, len);
    		}
    		byte[] array = bos.toByteArray();
    		bos.close();
    		return array;
    	}
    	/**
    	 * 功能:将InputStream转换成String
    	 * @param is
    	 * @return
    	 * @throws Exception
    	 */
    
    	public static String streamToString(InputStream is) throws Exception{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    		StringBuilder builder= new StringBuilder();
    		String line;
    		while((line=reader.readLine())!=null){ //当读取到 null时,就表示结束
    			builder.append(line+"\r\n");
    		}
    		return builder.toString();
    	}
    }
    
    
    • 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

    服务端

    public class TCPFileUploadServer {
        public static void main(String[] args) throws Exception {
    
            //1. 服务端在本机监听8888端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务端在8888端口监听....");
            //2. 等待连接
            Socket socket = serverSocket.accept();
    
    
            //3. 读取客户端发送的数据
            //   通过Socket得到输入流
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            byte[] bytes = StreamUtils.streamToByteArray(bis);
            //4. 将得到 bytes 数组,写入到指定的路径,就得到一个文件了
            String destFilePath = "src\\abc.mp4";
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
            bos.write(bytes);
            bos.close();
    
            // 向客户端回复 "收到图片"
            // 通过socket 获取到输出流(字符)
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            writer.write("收到图片");
            writer.flush();//把内容刷新到数据通道
            socket.shutdownOutput();//设置写入结束标记
    
            //关闭其他资源
            writer.close();
            bis.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
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    客户端

    public class TCPFileUploadClient {
        public static void main(String[] args) throws Exception {
    
            //客户端连接服务端 8888,得到Socket对象
            Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
            //创建读取磁盘文件的输入流
            //String filePath = "e:\\qie.png";
            String filePath = "e:\\abc.mp4";
            BufferedInputStream bis  = new BufferedInputStream(new FileInputStream(filePath));
    
            //bytes 就是filePath对应的字节数组
            byte[] bytes = StreamUtils.streamToByteArray(bis);
    
            //通过socket获取到输出流, 将bytes数据发送给服务端
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
            bos.write(bytes);//将文件对应的字节数组的内容,写入到数据通道
            bis.close();
            socket.shutdownOutput();//设置写入数据的结束标记
    
            //=====接收从服务端回复的消息=====
    
            InputStream inputStream = socket.getInputStream();
            //使用StreamUtils 的方法,直接将 inputStream 读取到的内容 转成字符串
            String s = StreamUtils.streamToString(inputStream);
            System.out.println(s);
    
    
            //关闭相关的流
            inputStream.close();
            bos.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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    4.5 netstat 指令

    image-20220216130817922

    4.6TCP网络通讯不为人知的秘密

    image-20220216130859586

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wg9PrH5H-1658245480048)(http://cdn.llinp.cn/imgs/imgs202202161309522.png)]

    5.UDP 网络通信编程[了解]

    5.1基本介绍

    image-20220216131005574

    5.2基本流程

    img

    5.3 应用案例

    image-20220216131141671

    接收端

    public class UDPReceiverA {
        public static void main(String[] args) throws IOException {
            //1. 创建一个 DatagramSocket 对象,准备在9999接收数据
            DatagramSocket socket = new DatagramSocket(9999);
            //2. 构建一个 DatagramPacket 对象,准备接收数据
            //   在前面讲解UDP 协议时,老师说过一个数据包最大 64k  这里数组定义最大是64*1024 ,但是案例占用没有这么大
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            //3. 调用 接收方法, 将通过网络传输的 DatagramPacket 对象
            //   填充到 packet对象
            //老师提示: 当有数据包发送到 本机的9999端口时,就会接收到数据
            //   如果没有数据包发送到 本机的9999端口, 就会阻塞等待.
            System.out.println("接收端A 等待接收数据..");
            socket.receive(packet);
    
            //4. 可以把packet 进行拆包,取出数据,并显示.
            int length = packet.getLength();//实际接收到的数据字节长度
            byte[] data = packet.getData();//接收到数据
            String s = new String(data, 0, length);
            System.out.println(s);
    
    
            //===回复信息给B端
            //将需要发送的数据,封装到 DatagramPacket对象
            data = "好的, 明天见".getBytes();
            //说明: 封装的 DatagramPacket对象 data 内容字节数组 , data.length , 主机(IP) , 端口
            packet =
                    new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 9998);
    
            socket.send(packet);//发送
    
            //5. 关闭资源
            socket.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
    • 33
    • 34
    • 35
    • 36
    • 37

    发送端

    public class UDPSenderB {
        public static void main(String[] args) throws IOException {
    
            //1.创建 DatagramSocket 对象,准备在9998端口 接收数据
            DatagramSocket socket = new DatagramSocket(9998);
    
            //2. 将需要发送的数据,封装到 DatagramPacket对象
            byte[] data = "hello 明天吃火锅~".getBytes(); //
            //说明: 封装的 DatagramPacket对象 data 内容字节数组 , data.length , 主机(IP) , 端口
            DatagramPacket packet =
                    new DatagramPacket(data, data.length, InetAddress.getLocalHost(), 9999);
    
            socket.send(packet);
    
            //3.=== 接收从A端回复的信息
            //(1)   构建一个 DatagramPacket 对象,准备接收数据
            //   在前面讲解UDP 协议时,老师说过一个数据包最大 64k
            byte[] buf = new byte[1024];
            packet = new DatagramPacket(buf, buf.length);
            //(2)    调用 接收方法, 将通过网络传输的 DatagramPacket 对象
            //   填充到 packet对象
            //老师提示: 当有数据包发送到 本机的9998端口时,就会接收到数据
            //   如果没有数据包发送到 本机的9998端口, 就会阻塞等待.
            socket.receive(packet);
    
            //(3)  可以把packet 进行拆包,取出数据,并显示.
            int length = packet.getLength();//实际接收到的数据字节长度
            data = packet.getData();//接收到数据
            String s = new String(data, 0, length);
            System.out.println(s);
    
            //关闭资源
            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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    6.三个练习题

    6.1练习题一

    image-20220216230237546

    服务端

    public class Homework01Server {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 在本机 的9999端口监听, 等待连接
            //   细节: 要求在本机没有其它服务在监听9999
            //   细节:这个 ServerSocket 可以通过 accept() 返回多个Socket[多个客户端连接服务器的并发]
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务端,在9999端口监听,等待连接..");
            //2. 当没有客户端连接9999端口时,程序会 阻塞, 等待连接
            //   如果有客户端连接,则会返回Socket对象,程序继续
    
            Socket socket = serverSocket.accept();
    
            //
            //3. 通过socket.getInputStream() 读取客户端写入到数据通道的数据, 显示
            InputStream inputStream = socket.getInputStream();
            //4. IO读取, 使用字符流, 老师使用 InputStreamReader 将 inputStream 转成字符流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();
            String answer = "";
            if ("name".equals(s)) {
                answer = "我是韩顺平";
            } else if("hobby".equals(s)) {
                answer = "编写java程序";
            } else {
                answer = "你说的啥子";
            }
    
    
            //5. 获取socket相关联的输出流
            OutputStream outputStream = socket.getOutputStream();
            //    使用字符输出流的方式回复信息
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(answer);
            bufferedWriter.newLine();// 插入一个换行符,表示回复内容的结束
            bufferedWriter.flush();//注意需要手动的flush
    
    
            //6.关闭流和socket
            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
    • 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

    客户端

    public class Homework01Client {
        public static void main(String[] args) throws IOException {
            //思路
            //1. 连接服务端 (ip , 端口)
            //解读: 连接本机的 9999端口, 如果连接成功,返回Socket对象
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
    
            //2. 连接上后,生成Socket, 通过socket.getOutputStream()
            //   得到 和 socket对象关联的输出流对象
            OutputStream outputStream = socket.getOutputStream();
            //3. 通过输出流,写入数据到 数据通道, 使用字符流
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
    
            //从键盘读取用户的问题
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你的问题");
            String question = scanner.next();
    
            bufferedWriter.write(question);
            bufferedWriter.newLine();//插入一个换行符,表示写入的内容结束, 注意,要求对方使用readLine()!!!!
            bufferedWriter.flush();// 如果使用的字符流,需要手动刷新,否则数据不会写入数据通道
    
    
            //4. 获取和socket关联的输入流. 读取数据(字符),并显示
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s = bufferedReader.readLine();
            System.out.println(s);
    
            //5. 关闭流对象和socket, 必须关闭
            bufferedReader.close();//关闭外层流
            bufferedWriter.close();
            socket.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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    6.2练习题二

    image-20220216230303238

    接受端

    public class Homework02ReceiverA {
        public static void main(String[] args) throws IOException {
            //1. 创建一个 DatagramSocket 对象,准备在8888接收数据
            DatagramSocket socket = new DatagramSocket(8888);
            //2. 构建一个 DatagramPacket 对象,准备接收数据
            //   在前面讲解UDP 协议时,老师说过一个数据包最大 64k
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            //3. 调用 接收方法, 将通过网络传输的 DatagramPacket 对象
            //   填充到 packet对象
            System.out.println("接收端 等待接收问题 ");
            socket.receive(packet);
    
            //4. 可以把packet 进行拆包,取出数据,并显示.
            int length = packet.getLength();//实际接收到的数据字节长度
            byte[] data = packet.getData();//接收到数据
            String s = new String(data, 0, length);
            //判断接收到的信息是什么
            String answer = "";
            if("四大名著是哪些".equals(s)) {
                answer = "四大名著 <<红楼梦>> <<三国演示>> <<西游记>> <<水浒传>>";
            } else {
                answer = "what?";
            }
    
    
            //===回复信息给B端
            //将需要发送的数据,封装到 DatagramPacket对象
            data = answer.getBytes();
            //说明: 封装的 DatagramPacket对象 data 内容字节数组 , data.length , 主机(IP) , 端口
            packet =
                    new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 9998);
    
            socket.send(packet);//发送
    
            //5. 关闭资源
            socket.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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    客户端

    public class Homework02SenderB {
        public static void main(String[] args) throws IOException {
    
            //1.创建 DatagramSocket 对象,准备在9998端口 接收数据
            DatagramSocket socket = new DatagramSocket(9998);
    
            //2. 将需要发送的数据,封装到 DatagramPacket对象
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你的问题: ");
            String question = scanner.next();
            byte[] data = question.getBytes(); //
    
            //说明: 封装的 DatagramPacket对象 data 内容字节数组 , data.length , 主机(IP) , 端口
            DatagramPacket packet =
                    new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 8888);
    
            socket.send(packet);
    
            //3.=== 接收从A端回复的信息
            //(1)   构建一个 DatagramPacket 对象,准备接收数据
            //   在前面讲解UDP 协议时,老师说过一个数据包最大 64k
            byte[] buf = new byte[1024];
            packet = new DatagramPacket(buf, buf.length);
            //(2)    调用 接收方法, 将通过网络传输的 DatagramPacket 对象
            //   填充到 packet对象
            //老师提示: 当有数据包发送到 本机的9998端口时,就会接收到数据
            //   如果没有数据包发送到 本机的9998端口, 就会阻塞等待.
            socket.receive(packet);
    
            //(3)  可以把packet 进行拆包,取出数据,并显示.
            int length = packet.getLength();//实际接收到的数据字节长度
            data = packet.getData();//接收到数据
            String s = new String(data, 0, length);
            System.out.println(s);
    
            //关闭资源
            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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    6.3练习题三

    image-20220216230318070

    服务端

    public class Homework03Server {
        public static void main(String[] args) throws Exception {
    
            //1 监听 9999端口
            ServerSocket serverSocket = new ServerSocket(9999);
            //2.等待客户端连接
            System.out.println("服务端,在9999端口监听,等待下载文件");
            Socket socket = serverSocket.accept();
            //3.读取 客户端发送要下载的文件名
            //  这里老师使用了while读取文件名,时考虑将来客户端发送的数据较大的情况
            InputStream inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            String downLoadFileName = "";
            while ((len = inputStream.read(b)) != -1) {
                downLoadFileName += new String(b, 0 , len);
            }
            System.out.println("客户端希望下载文件名=" + downLoadFileName);
    
            //老师在服务器上有两个文件, 无名.mp3 高山流水.mp3
            //如果客户下载的是 高山流水 我们就返回该文件,否则一律返回 无名.mp3
    
            String resFileName = "";
            if("高山流水".equals(downLoadFileName)) {
                resFileName = "src\\高山流水.mp3";
            } else {
                resFileName = "src\\无名.mp3";
            }
    
            //4. 创建一个输入流,读取文件
            BufferedInputStream bis =
                    new BufferedInputStream(new FileInputStream(resFileName));
    
            //5. 使用工具类StreamUtils ,读取文件到一个字节数组
    
            byte[] bytes = StreamUtils.streamToByteArray(bis);
            //6. 得到Socket关联的输出流
            BufferedOutputStream bos =
                    new BufferedOutputStream(socket.getOutputStream());
            //7. 写入到数据通道,返回给客户端
            bos.write(bytes);
            socket.shutdownOutput();//很关键.
    
            //8 关闭相关的资源
            bis.close();
            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
    • 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

    客户端

    public class Homework03Client {
        public static void main(String[] args) throws Exception {
    
    
            //1. 接收用户输入,指定下载文件名
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入下载文件名");
            String downloadFileName = scanner.next();
    
            //2. 客户端连接服务端,准备发送
            Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
            //3. 获取和Socket关联的输出流
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(downloadFileName.getBytes());
            //设置写入结束的标志
            socket.shutdownOutput();
    
            //4. 读取服务端返回的文件(字节数据)
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            byte[] bytes = StreamUtils.streamToByteArray(bis);
            //5. 得到一个输出流,准备将 bytes 写入到磁盘文件
            //比如你下载的是 高山流水 => 下载的就是 高山流水.mp3
            //    你下载的是 韩顺平 => 下载的就是 无名.mp3  文件名 韩顺平.mp3
            String filePath = "e:\\" + downloadFileName + ".mp3";
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
            bos.write(bytes);
    
            //6. 关闭相关的资源
            bos.close();
            bis.close();
            outputStream.close();
            socket.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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    python笔记
    【手动实现nn.Linear 】
    信息系统项目管理师Part13-UML
    公司注册类型分类标准是怎样的
    市场研究工具有哪些
    使用python制作epub
    建模杂谈系列157 关于“如何降低工作成本“的思考
    2171. 拿出最少数目的魔法豆-快速排序+前缀和
    AtCoder Beginner Contest 276「A」「B」「C」「D 思维」「E 联通块」「F 树状数组维护期望」
    在不损失质量的情况下减小PDF 文件大小的 6 种方法
  • 原文地址:https://blog.csdn.net/qq_44981526/article/details/125883430