JavaSE高阶篇-网络编程

初识重点

  1.知道自己将来开发的软件结构主要方向是啥
  2.知道TCP协议的3次握手
  3.会使用TCP协议编写一个简单的客户端和服务端之间的数据交互
  4.知道客户端和服务端之间的交互过程

一、软件结构

C/S结构 :全称为Client/Server结构,是指客户端和服务器结构。常见程序有QQ、红蜘蛛、飞秋等软件。

 B/S结构 :全称为Browser/Server结构,是指浏览器和服务器结构。常见浏览器有IE、谷歌、火狐等。

 

 【总结】

        两种架构各有优势,但是无论哪种架构,都离不开网络的支持。网络编程,就是在一定的协议下,实现两台计算机的通信的程序。

 二、服务器的概念

1.概述:安装了服务器软件的计算机
2.后续马上要接触到的服务器软件:tomcat

 网络通信协议:两台计算机在做数据交互时要遵守的规则,协议会对数据的格式,速率等进行规定,只有都遵守了这个协议,才能完成数据交互

两台计算机想完成数据交互,需要遵守网络通信协议

 

 三、通信三要素

1)基本概念

[IP地址]:计算机的唯一标识,用于两台计算机之间的连接

      a.概述:指互联网协议地址(Internet Protocol Address),俗称IP
            计算机的唯一标识
      b.作用:可用于计算机和计算机之间的连接
      c.IPV4
        32位的二进制数,通常被分为4个字节,表示成a.b.c.d 的形式,例如192.168.65.100 。其中a、b、c、d都是0~255之间的十进制整数,那么最多可以表示42亿个。
        IPV6
        为了扩大地址空间,拟通过IPv6重新定义地址空间,采用128位地址长度,每16个字节一组,分成8组十六进制数,表示成ABCD:EF01:2345:6789:ABCD:EF01:2345:6789->号称能给地球上的每一粒沙子分配一个IP地址
        
      d.查看ip的命令:ipconfig
        测试是否能连接其他计算机的命令:ping ip地址
        
      e:特殊的网址:代表的是本机地址,到了哪里都不会变,代表自己
        127.0.0.1 -> 固定不变
        localhost
        
        localhost:端口号/项目名/资源
        

[协议]
     TCP:面向连接协议
         需要先确认连接,才能进行数据交互
         三次握手:
            - 第一次握手,客户端向服务器端发出连接请求,等待服务器确认。
            - 第二次握手,服务器端向客户端回送一个响应,通知客户端收到了连接请求。
            - 第三次握手,客户端再次向服务器端发送确认信息,确认连接。
            
         好处:数据安全,能给数据的传输提供一个安全的传输环境
         坏处:效率低
     
     UDP:面向无连接协议
         好处:效率高
         坏处:传输的数据不安全,容易丢失数据包

[端口号]
   每一个应用程序的唯一标识
 
  用两个字节表示的整数,它的取值范围是0~65535。其中,0~1023之间的端口号用于一些知名的网络服务和应用,普通的应用程序需要使用1024以上的端口号。如果端口号被另外一个服务或应用所占用,会导致当前程序启动失败。

 

2)TCP协议中的三次握手和四次挥手

1-三次握手

三次握手:
- 第一次握手,客户端向服务器端发出连接请求,等待服务器确认。
- 第二次握手,服务器端向客户端回送一个响应,通知客户端收到了连接请求。
- 第三次握手,客户端再次向服务器端发送确认信息,确认连接。

 2-四次挥手

 四次挥手:
- 第一次挥手:客户端向服务器端提出结束连接,让服务器做最后的准备工作。此时,客户端处于半关闭状态,即表示不再向服务器发送数据了,但是还可以接受数据。
    
- 第二次挥手:服务器接收到客户端释放连接的请求后,会将最后的数据发给客户端。并告知上层的应用进程不再接收数据。
    
- 第三次挥手:服务器发送完数据后,会给客户端发送一个释放连接的报文。那么客户端接收后就知道可以正式释放连接了。
    
- 第四次挥手:客户端接收到服务器最后的释放连接报文后,要回复一个彻底断开的报文。这样服务器收到后才会彻底释放连接。这里客户端,发送完最后的报文后,会等待2MSL,因为有可能服务器没有收到最后的报文,那么服务器迟迟没收到,就会再次给客户端发送释放连接的报文,此时客户端在等待时间范围内接收到,会重新发送最后的报文,并重新计时。如果等待2MSL后,没有收到,那么彻底断开。

四、实现简单的客户端与服务端的交互

 

 1)编写客户端

 1.创建Socket对象,指明服务器的IP和端口号
 2.调用Socket中的getOutputStream,给服务器发送请求(写请求)
 3.调用Socket中的getInputStream,用于读取服务器响应回来的数据
 4.关闭资源

public class Client {
    public static void main(String[] args)throws Exception {
        //1.创建Socket对象,指明服务器的IP和端口号
        Socket socket = new Socket("127.0.0.1", 6666);
        //2.调用Socket中的getOutputStream,给服务器发送请求(写请求)
        OutputStream os = socket.getOutputStream();
        os.write("我想下载一个片儿".getBytes());
        //3.调用Socket中的getInputStream,用于读取服务器响应回来的数据
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(new String(bytes,0,len));
        //4.关闭资源
        is.close();
        os.close();
        socket.close();
    }
}

 2)编写服务端

1.创建ServerSocket对象,设置端口号
2.调用ServerSocket中的accept方法,等待客户端连接,返回socket对象
3.调用Socket中的getInputStream,用于读取客户端发送过来的数据
4.调用Socket中的getOutputStream,用于给客户端响应数据
5.关闭资源

public class Server {
    public static void main(String[] args)throws Exception {
        //1.创建ServerSocket对象,设置端口号
        ServerSocket ss = new ServerSocket(6666);
        //2.调用ServerSocket中的accept方法,等待客户端连接,返回socket对象
        Socket socket = ss.accept();
        //3.调用Socket中的getInputStream,用于读取客户端发送过来的数据
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(new String(bytes,0,len));
        //4.调用Socket中的getOutputStream,用于给客户端响应数据
        OutputStream os = socket.getOutputStream();
        os.write("给你一个三上主演的片儿".getBytes());
        //5.关闭资源
        os.close();
        is.close();
        socket.close();
        ss.close();
    }
}

五、文件上传

1)文件上传客户端以及服务端实现

public class Client {
    public static void main(String[] args)throws Exception {
        //1.创建Socket对象,指明服务端IP和端口号
        Socket socket = new Socket("127.0.0.1", 6666);
        //2.创建FileInputStream,用于读取本地上的图片
        FileInputStream fis = new FileInputStream("E:\\Idea\\io\\2.jpg");
        //3.调用getOutputStream用于将读取过来的图片写到服务端
        OutputStream os = socket.getOutputStream();
        //4.边读边写
        byte[] bytes1 = new byte[1024];
        int len;
        while((len = fis.read(bytes1))!=-1){
            os.write(bytes1,0,len);
        }

        socket.shutdownOutput();

        System.out.println("============以下代码为读取响应结果=============");

        //5.调用getInputStream,用于读取服务端发送过来的响应结果
        InputStream is = socket.getInputStream();
        byte[] bytes2 = new byte[1024];
        int len2 = is.read(bytes2);
        System.out.println(new String(bytes2,0,len2));

        //6.关闭资源
        is.close();
        os.close();
        fis.close();
        socket.close();

    }
}
/**
 * 服务端
 */
public class Server {
    public static void main(String[] args)throws Exception {
        //1.创建ServerSocket对象,设置端口号
        ServerSocket ss = new ServerSocket(6666);
        //2.调用accept方法等待客户端连接
        Socket socket = ss.accept();
        //3.调用getInputStream,用于读取客户端发送过来的图片字节
        InputStream is = socket.getInputStream();

        //UUID是一个工具类,可以生成随机的串儿
        UUID uuid = UUID.randomUUID();
        String name = uuid.toString();
        //4.创建FileOutputStream,用于将读取过来的图片写到本地上
        FileOutputStream fos = new FileOutputStream("E:\\Idea\\io\\upload\\"+name+".jpg");
        //5.边读边写
        byte[] bytes1 = new byte[1024];
        int len;
        while((len = is.read(bytes1))!=-1){
            fos.write(bytes1,0,len);
        }

        System.out.println("============以下代码为响应结果=============");

        //6.获取getOutputStream,用于给客户端响应数据
        OutputStream os = socket.getOutputStream();
        os.write("上传成功".getBytes());
        //7.关闭资源
        os.close();
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

 

 

2)文件上传服务端实现(多线程)

/**
 * 服务端
 */
public class Server_Thread {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象,设置端口号
        ServerSocket ss = new ServerSocket(6666);

        while (true) {
            //2.调用accept方法等待客户端连接
            Socket socket = ss.accept();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream is = null;
                    FileOutputStream fos = null;
                    OutputStream os = null;
                    try {
                        //3.调用getInputStream,用于读取客户端发送过来的图片字节
                        is = socket.getInputStream();

                        //UUID是一个工具类,可以生成随机的串儿
                        UUID uuid = UUID.randomUUID();
                        String name = uuid.toString();
                        //4.创建FileOutputStream,用于将读取过来的图片写到本地上
                        fos = new FileOutputStream("E:\\Idea\\io\\upload\\" + name + ".jpg");
                        //5.边读边写
                        byte[] bytes1 = new byte[1024];
                        int len;
                        while ((len = is.read(bytes1)) != -1) {
                            fos.write(bytes1, 0, len);
                        }

                        System.out.println("============以下代码为响应结果=============");

                        //6.获取getOutputStream,用于给客户端响应数据
                        os = socket.getOutputStream();
                        os.write("上传成功".getBytes());

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                       CloseUtils.closeUtils(os,fos,is,socket);
                    }
                }
            }).start();


        }

    }
}

 3)文件上传服务端(连接池版本)

/**
 * 服务端
 */
public class Server_ThreadPool {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象,设置端口号
        ServerSocket ss = new ServerSocket(6666);

        ExecutorService es = Executors.newFixedThreadPool(50);

        while (true) {
            //2.调用accept方法等待客户端连接
            Socket socket = ss.accept();

           es.submit(new Runnable() {
                @Override
                public void run() {
                    InputStream is = null;
                    FileOutputStream fos = null;
                    OutputStream os = null;
                    try {
                        //3.调用getInputStream,用于读取客户端发送过来的图片字节
                        is = socket.getInputStream();

                        //UUID是一个工具类,可以生成随机的串儿
                        UUID uuid = UUID.randomUUID();
                        String name = uuid.toString();
                        //4.创建FileOutputStream,用于将读取过来的图片写到本地上
                        fos = new FileOutputStream("E:\\Idea\\io\\upload\\" + name + ".jpg");
                        //5.边读边写
                        byte[] bytes1 = new byte[1024];
                        int len;
                        while ((len = is.read(bytes1)) != -1) {
                            fos.write(bytes1, 0, len);
                        }

                        System.out.println("============以下代码为响应结果=============");

                        //6.获取getOutputStream,用于给客户端响应数据
                        os = socket.getOutputStream();
                        os.write("上传成功".getBytes());

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                       CloseUtils.closeUtils(os,fos,is,socket);
                    }
                }
            });


        }

    }
}

4)关闭资源类

public class CloseUtils {
    private CloseUtils(){

    }
    public static void closeUtils(OutputStream os, FileOutputStream fos, InputStream is, Socket socket){
        //7.关闭资源
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (fos != null) {
            try {
                fos.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();
            }
        }

    }
}

六、BS架构服务器案例

1)案例分析)

 2)B/S结构服务器代码实现

/**
 * 1.我们想要的是调用BufferedReader中的readLine()方法,读取请求报文中的第一行数据
 *   GET /day21_Net/web/index.html HTTP/1.1
 *
 * 2.我们需要将InputStream转成BufferedReader对象,
 *   我们只需要想办法将InputStream放到BufferedReader的构造中就行了
 *
 * 3.BufferedReader的构造:
 *   BufferedReader(Reader r)
 *                  Reader的子类: FileReader
 *                               InputStreamReader->传递此转换流对象到BufferedReader中
 * 4.InputStreamReader构造:
 *   InputStreamReader(InputStream in)
 *
 * 5.怎么将InputStream转成BufferedReader
 *   new BufferedReader(new InputStreamReader(InputStream))
 *
 *
 *
 */
public class BSServer {
    public static void main(String[] args)throws Exception {
        //1.创建ServerSocket对象
        ServerSocket ss = new ServerSocket(8888);

        while(true){
            //2.调用accept,等待客户端连接
            Socket socket = ss.accept();
            //3.调用getInputStream,读取浏览器发送过来的请求
            InputStream in = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String s = br.readLine();//  GET /day21_Net/web/index.html HTTP/1.1
            String[] arr = s.split(" ");
            String s1 = arr[1];
            String path = s1.substring(1);//   day21_Net/web/index.html

            //4.根据解析出来的路径,创建FileInputStream读取本地上的html
            FileInputStream fis = new FileInputStream(path);
            //5.调用getOutputStream,将读取到的html写到浏览器上面
            OutputStream os = socket.getOutputStream();

            //给浏览器先写一个响应信息
            os.write("HTTP/1.1 200 OK\r\n".getBytes());
            os.write("Content-Type:text/html\r\n".getBytes());
            os.write("\r\n".getBytes());

            //6.边读边写
            byte[] bytes = new byte[1024];
            int len;
            while((len = fis.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
            //7.关闭资源
            os.close();
            fis.close();
            br.close();
            in.close();
            socket.close();
        }

    }
}

3)B/S服务器实现(多线程版本)

public class BSServer_Thread {
    public static void main(String[] args)throws Exception {
        //1.创建ServerSocket对象
        ServerSocket ss = new ServerSocket(8888);

        while(true){
            //2.调用accept,等待客户端连接
            Socket socket = ss.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream in = null;
                    BufferedReader br = null;
                    FileInputStream fis = null;
                    OutputStream os = null;
                    try{
                        //3.调用getInputStream,读取浏览器发送过来的请求
                        in = socket.getInputStream();
                        br = new BufferedReader(new InputStreamReader(in));
                        String s = br.readLine();//  GET /day21_Net/web/index.html HTTP/1.1
                        String[] arr = s.split(" ");
                        String s1 = arr[1];
                        String path = s1.substring(1);//   day21_Net/web/index.html

                        //4.根据解析出来的路径,创建FileInputStream读取本地上的html
                         fis = new FileInputStream(path);
                        //5.调用getOutputStream,将读取到的html写到浏览器上面
                        os = socket.getOutputStream();

                        //给浏览器先写一个响应信息
                        os.write("HTTP/1.1 200 OK\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        os.write("\r\n".getBytes());

                        //6.边读边写
                        byte[] bytes = new byte[1024];
                        int len;
                        while((len = fis.read(bytes))!=-1){
                            os.write(bytes,0,len);
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        //7.关闭资源
                        //os.close();
                        //fis.close();
                        //br.close();
                        //in.close();
                        //socket.close();
                        CloseUtils.closeUtils(os,null,fis,br,in,socket);
                    }

                }
            }).start();

        }

    }
}

4)B/S服务器实现(线程池实现)

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BSServer_Thread {

    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(10); // 创建固定大小的线程池

    public static void main(String[] args) throws Exception {
        // 1. 创建 ServerSocket 对象
        ServerSocket ss = new ServerSocket(8888);

        while (true) {
            // 2. 调用 accept,等待客户端连接
            Socket socket = ss.accept();

            // 3. 将处理客户端连接的任务提交给线程池
            THREAD_POOL.submit(() -> handleClientConnection(socket));
        }
    }

    private static void handleClientConnection(Socket socket) {
        InputStream in = null;
        BufferedReader br = null;
        FileInputStream fis = null;
        OutputStream os = null;

        try {
            // 3. 调用 getInputStream,读取浏览器发送过来的请求
            in = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(in));
            String s = br.readLine(); // GET /day21_Net/web/index.html HTTP/1.1
            String[] arr = s.split(" ");
            String s1 = arr[1];
            String path = s1.substring(1); // day21_Net/web/index.html

            // 4. 根据解析出来的路径,创建 FileInputStream 读取本地上的 html
            fis = new FileInputStream(path);
            // 5. 调用 getOutputStream,将读取到的 html 写到浏览器上面
            os = socket.getOutputStream();

            // 给浏览器先写一个响应信息
            os.write("HTTP/1.1 200 OK\r\n".getBytes());
            os.write("Content-Type:text/html\r\n".getBytes());
            os.write("\r\n".getBytes());

            // 6. 边读边写
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭资源
            CloseUtils.closeUtils(os, null, fis, br, in, socket);
        }
    }
}

        在这个版本中,我们首先创建了一个固定大小为 10 的线程池(可以根据实际需求调整线程池大小)。在主循环中,每当有新的客户端连接时,我们将处理该连接的任务封装为一个 lambda 表达式,并通过 THREAD_POOL.submit() 方法提交给线程池执行。这样,线程池会自动管理任务的分配和线程的复用,避免了频繁创建和销毁线程带来的开销。

 

修改关闭资源工具类
======================================
public class CloseUtils {
    private CloseUtils(){

    }
    public static void closeUtils(OutputStream os, FileOutputStream fos, FileInputStream fis,BufferedReader br, InputStream is, Socket socket){
        //7.关闭资源
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (fis!=null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (br!=null){
            try {
                br.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();
            }
        }

    }
}

 结束语

写的不好的 多多包涵奥

  • 10
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值