Java之UDP,TCP的详细解析

news/2024/5/18 11:52:19 标签: java, 开发语言, tcp/ip, 网络协议, 笔记, udp

练习四:文件名重复

java">public class UUIDTest { public static void main(String[] args) { String str = UUID.randomUUID().toString().replace("-", ""); System.out.println(str);//9f15b8c356c54f55bfcb0ee3023fce8a } } ```

public class Client {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //1. 创建Socket对象,并连接服务器
        Socket socket = new Socket("127.0.0.1",10000);
​
        //2.读取本地文件中的数据,并写到服务器当中
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mysocketnet\\clientdir\\a.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
​
        //往服务器写出结束标记
        socket.shutdownOutput();
​
​
        //3.接收服务器的回写数据
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println(line);
​
​
        //4.释放资源
        socket.close();
​
    }
}
public class Server {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //1.创建对象并绑定端口
        ServerSocket ss = new ServerSocket(10000);
​
        //2.等待客户端来连接
        Socket socket = ss.accept();
​
        //3.读取数据并保存到本地文件中
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        String name = UUID.randomUUID().toString().replace("-", "");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mysocketnet\\serverdir\\" + name + ".jpg"));
        int len;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        bos.close();
        //4.回写数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("上传成功");
        bw.newLine();
        bw.flush();
​
        //5.释放资源
        socket.close();
        ss.close();
    }
}

练习五:服务器改写为多线程

服务器只能处理一个客户端请求,接收完一个图片之后,服务器就关闭了。

优化方案一:

使用循环

弊端:

第一个用户正在上传数据,第二个用户就来访问了,此时第二个用户是无法成功上传的。

所以,使用多线程改进

优化方案二:

每来一个用户,就开启多线程处理

java">public class Client {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //1. 创建Socket对象,并连接服务器
        Socket socket = new Socket("127.0.0.1",10000);
​
        //2.读取本地文件中的数据,并写到服务器当中
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mysocketnet\\clientdir\\a.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
​
        //往服务器写出结束标记
        socket.shutdownOutput();
​
​
        //3.接收服务器的回写数据
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println(line);
​
​
        //4.释放资源
        socket.close();
​
    }
}
public class Server {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //1.创建对象并绑定端口
        ServerSocket ss = new ServerSocket(10000);
​
        while (true) {
            //2.等待客户端来连接
            Socket socket = ss.accept();
​
            //开启一条线程
            //一个用户就对应服务端的一条线程
            new Thread(new MyRunnable(socket)).start();
        }
​
    }
}
​
​
public class MyRunnable implements Runnable{
​
    Socket socket;
​
    public MyRunnable(Socket socket){
        this.socket = socket;
    }
​
    @Override
    public void run() {
        try {
            //3.读取数据并保存到本地文件中
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mysocketnet\\serverdir\\" + name + ".jpg"));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bos.close();
            //4.回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
           if(socket != null){
               try {
                   socket.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }
    }
}

练习六:线程池改进

java">public class Client {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //1. 创建Socket对象,并连接服务器
        Socket socket = new Socket("127.0.0.1",10000);
​
        //2.读取本地文件中的数据,并写到服务器当中
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mysocketnet\\clientdir\\a.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
​
        //往服务器写出结束标记
        socket.shutdownOutput();
​
​
        //3.接收服务器的回写数据
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println(line);
​
​
        //4.释放资源
        socket.close();
​
    }
}
public class Server {
    public static void main(String[] args) throws IOException {
        //客户端:将本地文件上传到服务器。接收服务器的反馈。
        //服务器:接收客户端上传的文件,上传完毕之后给出反馈。
​
​
        //创建线程池对象
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3,//核心线程数量
                16,//线程池总大小
                60,//空闲时间
                TimeUnit.SECONDS,//空闲时间(单位)
                new ArrayBlockingQueue<>(2),//队列
                Executors.defaultThreadFactory(),//线程工厂,让线程池如何创建线程对象
                new ThreadPoolExecutor.AbortPolicy()//阻塞队列
        );
​
​
​
        //1.创建对象并绑定端口
        ServerSocket ss = new ServerSocket(10000);
​
        while (true) {
            //2.等待客户端来连接
            Socket socket = ss.accept();
​
            //开启一条线程
            //一个用户就对应服务端的一条线程
            //new Thread(new MyRunnable(socket)).start();
            pool.submit(new MyRunnable(socket));
        }
​
    }
}
public class MyRunnable implements Runnable{
​
    Socket socket;
​
    public MyRunnable(Socket socket){
        this.socket = socket;
    }
​
    @Override
    public void run() {
        try {
            //3.读取数据并保存到本地文件中
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mysocketnet\\serverdir\\" + name + ".jpg"));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bos.close();
            //4.回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
           if(socket != null){
               try {
                   socket.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }
    }
}

http://www.niftyadmin.cn/n/5074635.html

相关文章

Haar cascade+opencv检测算法

Harr特征识别人脸 Haar cascade opencv步骤 读取包含人脸的图片使用haar模型识别人脸将识别的结果用矩形框画出来 构造haar检测器 &#xff1a;cv2.CascadeClassifier(具体检测模型文件) # 构造Haar检测器 # 级联分级机,cv2.CascadeClassifier():cv2的内置方法&#xff0…

使用nvm安装多个node版本

github下载地址: Releases coreybutler/nvm-windows (github.com) 安装了 nvm&#xff08;Node Version Manager&#xff09;后&#xff0c;可以使用以下步骤安装第二个 Node.js 版本&#xff1a; 打开终端或命令提示符。 使用以下命令列出可用的 Node.js 版本&#xff1a; …

【java学习】循环结构和嵌套循环(7)

文章目录 1.循环结构2. 三种循环语句2.1. for循环语句2.2. while循环语句2.3. do-while循环语句 3. 无限循环语句方式4. 嵌套循环 1.循环结构 1.1. 循环语句功能     在某些条件下&#xff0c;反复执行特定代码的功能 1.2. 循环语句的四个组成部分     (1) 初始化部分…

如何实现 Es 全文检索、高亮文本略缩处理

如何实现 Es 全文检索、高亮文本略缩处理 前言技术选型JAVA 常用语法说明全文检索开发高亮开发Es Map 转对象使用核心代码 Trans 接口&#xff08;支持父类属性的复杂映射&#xff09;Trans 接口的不足真实项目落地效果 前言 最近手上在做 Es 全文检索的需求&#xff0c;类似于…

50KW 车载模块化负载箱

模块化负载采用进口工业防护外箱作为主箱体框架&#xff0c;使设备具有良好的安全防护绝缘性能和减震抗震效果&#xff0c;满足常规的实验室工厂使用外&#xff0c;适用于复杂的工作环境如车载&#xff0c;户外应用等特殊场合。模块负载支持垂直堆叠式组合放置&#xff0c;可以…

Vue中引入jQuery两种方式可在vue中引入jQuery

第一种&#xff1a;普通html中使用jquery 将jQuer的文件导入到项目中&#xff0c;然后直接使用<script src"jQuery.js"></script>即可。 第二种&#xff1a;vue组件中使用jquery 1、安装依赖 cnpm install jquery --save 或者 npm install jquery --save…

manual control lost 飞机乱飞

Gazebo或jmavsim里仿真都这样&#xff0c;突然QGC会出现 manual control lost&#xff0c;然后飞机会乱飞 解决方案1&#xff1a; 把 NAV_RCL_ACT 设置为 Disable&#xff0c;相当于关闭遥控器丢失失效保护&#xff0c;默认是Return返航&#xff0c;所以会乱飞。 解决方案2&a…

ansible模块示例及说明

1. 文件操作&#xff1a; 复制文件到目标主机&#xff1a; - name: Copy a file ansible.builtin.copy: src: /path/to/source/file dest: /path/to/destination/file 创建目录&#xff1a; - name: Create a directory ansible.builtin.file: path: /path/to…