Java 第九章 网络编程(2)

news/2025/2/22 5:21:44

目录

网络编程

TCP编程

实例(发送文件)

UDP编程

理解

流 程:

发送端

接收端


网络编程


TCP编程

实例(发送文件)

java">public class Client {
    public static void main(String[] args) {
        // 在客户端输入一个文件
        try {
            FileInputStream inputStream = new FileInputStream("E:/A.png");
            Socket socket = new Socket("127.0.0.1",9999);
            OutputStream outputStream = socket.getOutputStream();
            byte[] bytes = new  byte[1024];
            int length=0;
            while ((length=inputStream.read(bytes))!=-1 ){
                outputStream.write(bytes, 0,length);
            }
            socket.shutdownOutput();//发送文件时,需要调用,表示发送完成
            //接收服务器返回的消息
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            System.out.println(dataInputStream.readUTF());
        } catch (FileNotFoundException e) {
            System.out.println("文件找不到");
        } catch (UnknownHostException e) {
            System.out.println("IP不正确");
        } catch (IOException e) {
            System.out.println("网络忙,请稍后再试");
        }
    }
}

public class Sever {
    public static void main(String[] args) {
        try {
            ServerSocket sever = new ServerSocket(9999);
            System.out.println("服务器启动");
            Socket socket = sever.accept();
            System.out.println("客户端链接成功");
            FileOutputStream outputStream= new FileOutputStream("E:/a.png");
            InputStream inputStream = socket.getInputStream();
            byte []bytes = new byte[100];
            int length= 0;
            while ((length = inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,length);
            }
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF("接收成功 ");

        } catch (IOException e) {
            System.out.println();
        }


    }
}

UDP编程

理解

  • 类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。
  • UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP 数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
  •  DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址 和端口号以及接收端的IP地址和端口号。
  • UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方 的连接

流 程:

  1. DatagramSocket与DatagramPacket
  2. 建立发送端,接收端
  3.  建立数据报
  4.  调用Socket的发送、接收方法
  5. 关闭Socket
  6. 发送端与接收端是两个独立的运行程序
发送端
  • DatagramSocket ds = new DatagramSocket();
  • byte[] by = “hello,baidu.com”.getBytes();
  • DatagramPacket dp = new DatagramPacket(by,0,by.length,InetAddress.getByName(“127.0.0.1”),10000);
  • ds.send(dp);
  • ds.close();
java">public class Send {
    public static void main(String[] args) {
        try {
            DatagramSocket datagramSocket = new DatagramSocket();
            byte []bytes="你好".getBytes();
            while (true) {
                //创建数据包对象
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), 9999);
                datagramSocket.send(datagramPacket);
            }
        } catch (SocketException e) {
            System.out.println("404");
            e.getMessage();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
接收端

(要指定监听的端口)

  • DatagramSocket ds = new DatagramSocket(10000);
  • byte[] by = new byte[1024];
  • DatagramPacket dp = new DatagramPacket(by,by.length);
  • ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength());
  • System.out.println(str+"--"+dp.getAddress()); ds.close()
java">public class Receive {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        byte[] bytes = new byte[100];
        while (true){
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        datagramSocket.receive(datagramPacket);//接收数据到数据包
        String s = new String(bytes,0,datagramPacket.getLength());
        System.out.println(s);
        }
    }
}

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

相关文章

使用Python进行PDF隐私信息检测

在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要。本文将介绍如何使用Python及其相关库来检测PDF文件中的隐私信息,如姓名、身份证号、手机号和邮箱等。 C:\pythoncode\new\checkp…

Hopper架构 GEMM教程

一 使用 1.1 makefile compile:nvcc -arch=sm_90a -lcuda -lcublas -std=c++17 matmul_h100_optimal.cu -o testrun:./test加入-lcublas,不然会有函数无法被识别 二 代码分析 2.1 kernel外参数分析 2.1.1 基本参数 constexpr int BM = 64*2;constexpr int BN = 256;cons…

React fiber架构中 优先级是如何确定的?

React fiber架构中 优先级是如何确定的? 在React Fiber架构中,优先级的确定是一个复杂而精细的过程,它涉及多种因素和策略。以下是对React Fiber中优先级确定方式的详细分析: 一、优先级类型与划分 React Fiber为不同的任务分配了不同的优…

使用(xshell+xftp)将前端项目部署到服务器

一.以vue项目为例 将项目打包生成dist文件 二.下载载安装xshell和xftp 下载地址:家庭/学校免费 - NetSarang Website 三.连接服务器 在xshell新建会话(需要用到服务器、用户名、密码、端口号)正确输入后连接到服务器 使用命令连接&#x…

angular中使用animation.css实现翻转展示卡片正反两面效果

html <div(click)"flip()"class"animate__animated cursor--pointer"[ngClass]"{ animate__flipInX: isFlipped }" ><div *ngIf"!isFlipped">正面</div><div *ngIf"isFlipped">背面</div> …

店铺矩阵崩塌前夜:跨境多账号运营的3个生死线

多账号运营的3条生死线&#xff0c;跨境卫士助你避开矩阵崩塌危机&#xff01; 在跨境电商行业&#xff0c;多账号运营是许多卖家扩大规模、分散风险的常用策略。然而&#xff0c;随着平台风控的日益严格&#xff0c;多账号运营的风险也在不断加剧。近期&#xff0c;某知名卖家…

Apifox 增强 AI 接口调试功能:自动合并 SSE 响应、展示DeepSeek思考过程

在API调试的世界里&#xff0c;效率和准确性往往决定了开发者的成败。你是否曾为处理SSE&#xff08;Server-Sent Events&#xff09;响应而烦恼&#xff1f;又是否期待在调试时能直观看到AI的“思考过程”&#xff1f;Apifox这次全新升级&#xff0c;将AI接口调试功能推向新高…

人工智能丨OCR 的业务场景,实现原理和测试指标

OCR 的业务场景 OCR&#xff08;光学字符识别&#xff09;技术广泛应用于多个领域&#xff0c;主要业务场景包括&#xff1a; 金融行业&#xff1a; 票据识别&#xff1a;自动识别发票、支票、收据等。身份验证&#xff1a;识别身份证、护照、驾驶证等证件信息。 医疗行业&am…