UDP通信(二)中

简介: UDP通信(二)

二.二 发送多条不同类型的数据


二.二.一 客户端


@Test
    public void send2Test() throws Exception{
        //1. 定义客户端
        System.out.println("------------发送方开始发送多条数据--------------");
        DatagramSocket datagramSocket=new DatagramSocket(6666);
        //2. 准备数据
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        //封装数据
        DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(byteArrayOutputStream));
        dataOutputStream.writeUTF("两个蝴蝶飞");
        dataOutputStream.writeInt(24);
        dataOutputStream.writeDouble(95.5);
        dataOutputStream.writeChar('男');
        dataOutputStream.writeUTF("一个快乐的程序员");
        //一定不要忘记刷新
        dataOutputStream.flush();
        //3. 将数据转换成字节数据
        byte[] bytes=byteArrayOutputStream.toByteArray();
        //   System.out.println("发送数据为:"+new String(bytes));
        //4. 封装进包
        InetSocketAddress inetSocketAddress=new InetSocketAddress("localhost",9999);
        DatagramPacket datagramPacket=new DatagramPacket(bytes,0,bytes.length,inetSocketAddress);
        datagramSocket.send(datagramPacket);
        //关闭流
        datagramSocket.close();
    }


二.二.二 服务端


@Test
    public void send2Test() throws Exception{
        //1. 定义服务器
        System.out.println("---------------服务器启动成功,接收多条数据----------------");
        DatagramSocket datagramSocket=new DatagramSocket(9999);
        //2. 设置数据
        byte[] bytes=new byte[1024];
        //能接收的大小,并不是实际接收的大小
        DatagramPacket datagramPacket=new DatagramPacket(bytes,0,bytes.length);
        //3. 阻塞式接收传递过来的数据
        datagramSocket.receive(datagramPacket);
        //4. 获取接收的数据
        byte[] content=datagramPacket.getData();
        int len=datagramPacket.getLength();
       // System.out.println("数据是:"+ new String(content,0,content.length)+",长度是:"+len);
       //将数据放置到内存里面
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(content);
        DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(byteArrayInputStream));
        //读取数据
        String name=dataInputStream.readUTF();
        int age=dataInputStream.readInt();
        double score=dataInputStream.readDouble();
        char sex=dataInputStream.readChar();
        String desc=dataInputStream.readUTF();
        System.out.printf("姓名是:%s,年龄是:%d,成绩是:%f,性别是:%c,描述是:%s",name,age,score,sex,desc);
        //5 关闭流
        datagramSocket.close();
    }


二.二.三 运行程序


运行服务器端, 后运行客户端, 查看服务器端数据输出:


20200625121854557.png


二.三 发送对象数据


有一个 Person 类, 还是具有 id,name,sex,age,desc 等属性


二.三.一 客户端


    @Test
    public void send3Test() throws Exception{
        //1. 定义客户端
        System.out.println("------------发送方开始发送对象数据--------------");
        DatagramSocket datagramSocket=new DatagramSocket(6666);
        //2. 准备数据
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(new BufferedOutputStream(byteArrayOutputStream));
       //放入对象
        Person person=new Person();
        person.setId(1);
        person.setName("两个蝴蝶飞");
        person.setSex('男');
        person.setAge(24);
        person.setDesc("一个快乐的程序员");
        objectOutputStream.writeObject(person);
        //放置日期
        objectOutputStream.writeObject(new Date());
        //一定不要忘记刷新
        objectOutputStream.flush();
        //3. 将数据转换成字节数据
        byte[] bytes=byteArrayOutputStream.toByteArray();
        //   System.out.println("发送数据为:"+new String(bytes));
        //4. 封装进包
        InetSocketAddress inetSocketAddress=new InetSocketAddress("localhost",9999);
        DatagramPacket datagramPacket=new DatagramPacket(bytes,0,bytes.length,inetSocketAddress);
        datagramSocket.send(datagramPacket);
        //关闭流
        datagramSocket.close();
    }


二.三.二 服务器端


  @Test
    public void send3Test() throws Exception{
        //1. 定义服务器
        System.out.println("---------------服务器启动成功,接收对象数据----------------");
        DatagramSocket datagramSocket=new DatagramSocket(9999);
        //2. 设置数据
        byte[] bytes=new byte[1024];
        //能接收的大小,并不是实际接收的大小
        DatagramPacket datagramPacket=new DatagramPacket(bytes,0,bytes.length);
        //3. 阻塞式接收传递过来的数据
        datagramSocket.receive(datagramPacket);
        //4. 获取接收的数据
        byte[] content=datagramPacket.getData();
        int len=datagramPacket.getLength();
        //将数据放置到内存里面
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(content);
        ObjectInputStream objectInputStream=new ObjectInputStream(new BufferedInputStream(byteArrayInputStream));
        //读取数据
        Object obj1=objectInputStream.readObject();
        if(obj1 instanceof Person){
            Person person=(Person)obj1;
            System.out.println(person.toString());
        }else{
            System.out.println("接收格式有误");
        }
        Object obj2=objectInputStream.readObject();
        if(obj2 instanceof Date){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("日期:"+sdf.format((Date)obj2));
        }else{
            System.out.println("接收格式有误");
        }
        //5 关闭流
        datagramSocket.close();
    }


二.三.三 运行程序


运行服务器端, 后运行客户端, 查看服务器端数据输出:


20200625121902252.png


二.四 发送图片文件


### 二.四.一 文件工具类 IOUtils


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
 *1、 图片读取到字节数组
 *2、 字节数组写出到文件
 *  @author 两个蝴蝶飞
 *
 */
public class IOUtils {
  /**
   * 1、文件,一般为图片 读取到字节数组
   * 1)、图片到程序  FileInputStream
   * 2)、程序到字节数组 ByteArrayOutputStream
   */
  public static byte[] fileToByteArray(String filePath) {
    //1、创建源与目的地
    File src = new File(filePath);
    byte[] dest =null;
    //2、选择流
    InputStream  is =null;
    ByteArrayOutputStream baos =null;
    try {
      is =new FileInputStream(src);
      baos = new ByteArrayOutputStream();
      //3、操作 (分段读取)
      byte[] flush = new byte[1024*10]; //缓冲容器
      int len = -1; //接收长度
      while((len=is.read(flush))!=-1) {
        baos.write(flush,0,len);     //写出到字节数组中     
      }   
      baos.flush();
      return baos.toByteArray();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      //4、释放资源
      try {
        if(null!=is) {
          is.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;    
  }
  /**
   * 2、字节数组写入到文件
   * 1)、字节数组到程序 ByteArrayInputStream
   * 2)、程序到文件 FileOutputStream
   */
  public static void byteArrayToFile(byte[] src,String filePath) {
    //1、创建源
    File dest = new File(filePath);
    //2、选择流
    InputStream  is =null;
    OutputStream os =null;
    try {
      is =new ByteArrayInputStream(src);
      os = new FileOutputStream(dest);
      //3、操作 (分段读取)
      byte[] flush = new byte[5]; //缓冲容器
      int len = -1; //接收长度
      while((len=is.read(flush))!=-1) {
        os.write(flush,0,len);      //写出到文件 
      }   
      os.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      //4、释放资源
      try {
        if (null != os) {
          os.close();
        } 
      } catch (Exception e) {
      }
    }
  }
}



相关文章
|
1月前
|
网络协议 算法 Java
【Java网络编程】网络编程概述、UDP通信(DatagramPacket 与 DatagramSocket)
【Java网络编程】网络编程概述、UDP通信(DatagramPacket 与 DatagramSocket)
31 3
|
11天前
UDP通信
UDP通信
8 1
|
24天前
|
网络协议 安全 Java
网络编程、网络编程的三要素、TCP/UDP通信、三次握手和四次挥手
网络编程、网络编程的三要素、TCP/UDP通信、三次握手和四次挥手
28 1
网络编程、网络编程的三要素、TCP/UDP通信、三次握手和四次挥手
|
1月前
|
存储 网络协议 关系型数据库
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
|
9月前
|
网络协议 Java
Java UDP通信详解
UDP(User Datagram Protocol)是一种无连接的网络传输协议,它不像TCP那样需要建立连接和维护状态,因此更加轻量级。UDP适用于那些对数据传输的实时性要求较高,可以容忍一定数据丢失的场景。本文将详细介绍Java中如何使用UDP协议进行网络通信,包括UDP套接字、数据传输、服务器和客户端的创建等。
146 0
|
1月前
UDP通信程序练习(实现模拟聊天室)
UDP通信程序练习(实现模拟聊天室)
64 0
|
1月前
|
存储 网络协议 Java
UDP通信程序的详细解析
2.UDP通信程序 2.1 UDP发送数据 Java中的UDP通信 UDP协议是一种不可靠的网络协议,它在通信的两端各建立一个Socket对象,但是这两个Socket只是发送,接收数据的对象,因此对于基于UDP协议的通信双方而言,没有所谓的客户端和服务器的概念
44 0
|
6月前
|
C语言
UDP通信原理及网络编程
UDP通信原理及网络编程
59 0
|
8月前
|
存储 网络协议 安全
UDP通信机制详解
UDP通信机制详解
205 0
|
9月前
|
网络协议 安全
基于TCP和UDP的Socket通信
TCP是面向连接的,安全的协议,它是一对一的关系 udp是面向无连接的,不安全,不可靠的,但是效率很高,支持一对一,一对多,多对多发送,udp传输的格式为数据报,要将其封装为数据报才能发送,
56 1