网络编程(二)基于UDP的Socket编程

版权声明:这里只是小白学习记录笔记资源的位置,若有问题请大佬们指点(●'◡'●) https://blog.csdn.net/weixin_42448414/article/details/84948892

Socket编程

基于UDP的Socket编程

基于UDP协议的Socket网络编程
不需要利用IO流实现数据的传输
每个数据发送单元被统一封装成数据包的方式,发送放将数据包发送到网络中,数据包在网络中去寻找他的目的地

package upd;

import java.io.*;

/***********************************
 * @description: 文件处理工具类
 **********************************/
public class FileIOUtil {
    public static byte[] fileToByteArray(String filePath) {
        // 1.创建源及地址
        File f = new File(filePath);
        byte[] b = null;
        // 2.创建流
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            is = new FileInputStream(f);
            baos = new ByteArrayOutputStream();
            // 3.分段读取
            // 缓冲容器
            byte[] bytes = new byte[1024 * 60];
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                // 写出到字节数组中
                baos.write(bytes, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void byteArrayToFile(byte[] bytes, String filePath) {
        // 1.创建源
        File f = new File(filePath);
        // 2.创建流
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = new ByteArrayInputStream(bytes);
            fos = new FileOutputStream(f);
            // 3.分段读取
            // 缓冲容器
            byte[] b = new byte[5];
            int len = -1;
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fos.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4.释放资源
            try {
                if (null != fos) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

package upd;

import java.io.Serializable;


public class Students implements Serializable {
    private String name;
    private String sex;
    private Integer age;

    public Students(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

package upd;

import org.junit.Test;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/***********************************
 *
 * @description: 基于UDP的Socket编程 - client
 *
 **********************************/

public class UdpClient {
    /**
     *
     * 发送端
     * 1.使用 DatagramSocket 指定端口 创建接收端
     * 2.准备数据,转成字节数组
     * 3.封装成 DatagramPacket 包裹,指定目的地
     * 4.发送包裹 send(DatagramPacket d)
     * 5.释放资源
     *
     * */
    public static void main(String[] args) {
        System.out.println("启动发送方:");
        DatagramSocket client = null;
        try {
            client = new DatagramSocket(8080);

            String data = "我是发送方!!!";
            byte[] bytes = data.getBytes();

            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                    new InetSocketAddress("localhost", 8081));
            client.send(packet);
            System.out.println("发送的数据:");
            System.out.println("\t" + new String(bytes));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    @Test
    public void testType() {
        System.out.println("启动发送方:");
        DatagramSocket client = null;
        try {
            client = new DatagramSocket(8080);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(baos));
            dos.writeUTF("典韦");
            dos.writeInt(18);
            dos.writeBoolean(true);
            dos.writeChar('a');
            dos.writeChars("abc");
            dos.flush();
            byte[] toByteArray = baos.toByteArray();

            DatagramPacket packet = new DatagramPacket(toByteArray, 0, toByteArray.length,
                    new InetSocketAddress("localhost", 8081));
            client.send(packet);
            System.out.println("发送的数据:");
            System.out.println("\t" + new String(toByteArray));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    @Test
    public void testObj() {
        System.out.println("启动发送方:");
        DatagramSocket client = null;
        try {
            client = new DatagramSocket(8080);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));

            Students s = new Students("典韦", "男", 18);
            oos.writeObject(s);

            oos.flush();

            byte[] toByteArray = baos.toByteArray();

            DatagramPacket packet = new DatagramPacket(toByteArray, 0, toByteArray.length,
                    new InetSocketAddress("localhost", 8081));
            client.send(packet);
            System.out.println("发送的数据:");
            System.out.println("\t" + s.toString());
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    @Test
    public void testFile() {
        System.out.println("启动发送方:");
        // 1.创建客户端
        DatagramSocket client = null;
        try {
            client = new DatagramSocket(8080);

            // 2.准备数据
            byte[] bytes = FileIOUtil.fileToByteArray("src/file.png");
            // 3.封装数据
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                    new InetSocketAddress("localhost", 8081));
            // 4.发送数据
            client.send(packet);
            System.out.println("发送的数据:");
            System.out.println("\t" + bytes);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5.释放资源
            client.close();
        }
    }
}

package upd;

import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/***********************************
 *
 * @description: 基于UDP的Socket编程 - service
 *
 **********************************/

public class UdpService {
    /**
     *
     * 接收端
     * 1.使用 DatagramSocket 指定端口 创建接收端
     * 2.准备容器,封装成 DatagramPacket 包裹
     * 3.阻塞式接收包裹 receive(DatagramPacket d)
     * 4.分析数据
     *      byte[] getData()
     *              getLength()
     * 5.释放资源
     *
     * */
    public static void main(String[] args) throws Exception{
        System.out.println("启动接收方:");
        DatagramSocket service = new DatagramSocket(8081);
        byte[] bytes = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        service.receive(packet);

        byte[] data = packet.getData();
        int length = packet.getLength();
        String s = new String(data, 0, length);

        service.close();
        System.out.println("接收的数据:");
        System.out.println("\t" + s);
    }

    @Test
    public void testType() throws Exception{
        System.out.println("启动接收方:");
        DatagramSocket service = new DatagramSocket(8081);
        byte[] bytes = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        service.receive(packet);

        byte[] data = packet.getData();
        int length = packet.getLength();

        DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(data)));
        String s1 = dis.readUTF();
        int i = dis.readInt();
        boolean b = dis.readBoolean();
        char c = dis.readChar();


        service.close();
        System.out.println("接收的数据:");
        System.out.println(s1);
        System.out.println(i);
        System.out.println(b);
        System.out.println(c);
    }

    @Test
    public void testObj() throws Exception{
        System.out.println("启动接收方:");
        DatagramSocket service = new DatagramSocket(8081);
        byte[] bytes = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        service.receive(packet);

        byte[] data = packet.getData();
        int length = packet.getLength();

        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(data)));

        Students s = (Students) ois.readObject();

        service.close();
        System.out.println("接收的数据:");
        System.out.println(s);

    }

    @Test
    public void testFile() throws Exception {
        System.out.println("启动接收方:");
        // 1.创建接收端
        DatagramSocket service = new DatagramSocket(8081);
        // 2.创建容器 封装
        byte[] bytes = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        // 3.阻塞式接收包裹
        service.receive(packet);
        // 4.分析数据
        byte[] data = packet.getData();
        int len = packet.getLength();
        FileIOUtil.byteArrayToFile(data, "src/file.png");
        service.close();
    }
}

多次发送

/***********************************
 * 接收端
 **********************************/
public class TalkServer {

    public static void main(String[] args) throws Exception {
        System.out.println("接收端:");
        DatagramSocket server = new DatagramSocket(8888);

        while (true) {
            byte[] bytes = new byte[1024 * 60];
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
            server.receive(packet);
            byte[] data = packet.getData();
            int length = packet.getLength();
            String s = new String(data, 0 , length);
            System.out.println(s);
            if (s.equals("bye")) {
                break;
            }
        }
        server.close();
    }
}

/***********************************
 * 发送端
 **********************************/
public class TalkClient {

    public static void main(String[] args) throws Exception {
        System.out.println("发送端:");
        DatagramSocket client = new DatagramSocket(9999);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String s = reader.readLine();
            byte[] bytes = s.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                    new InetSocketAddress("localhost", 8888));
            client.send(packet);
            if (s.equals("bye")) {
                break;
            }
        }
        client.close();
    }
}

多次发送,可互相发送

// 使用多线程,先封装发送和接收对象
/***********************************
 * 接收
 **********************************/
public class TalkReceive implements Runnable {
    private DatagramSocket server;
    private String from;
    public TalkReceive(int port, String from) {
        this.from = from;
        try {
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            byte[] bytes = new byte[1024 * 64];
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
            try {
                server.receive(packet);
                byte[] data = packet.getData();
                int length = packet.getLength();
                String string = new String(data, 0, length);
                System.out.println(from + ":" + string);
                if ("bye".equals(string)) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        server.close();
    }
}
/***********************************
 * 发送
 **********************************/
public class TalkSend implements Runnable {
    private DatagramSocket client;
    private int port;
    private String ip;
    private BufferedReader reader;

    public TalkSend(int port, String ip, int toPort) {
        this.port = port;
        this.ip = ip;
        try {
            client = new DatagramSocket(toPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            String s = null;
            try {
                s = reader.readLine();
                byte[] bytes = s.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                        new InetSocketAddress(this.ip, this.port));
                client.send(packet);
                if ("bye".equals(s)) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        client.close();
    }
}
/***********************************
 * 开始通信
 **********************************/
 public class TalksOne {
    public static void main(String[] args) {
        new Thread(new TalkSend(8888, "localhost", 6666)).start();
        new Thread(new TalkReceive(9999, "One")).start();
    }
}

public class TalksTwo {
    public static void main(String[] args) {
        new Thread(new TalkReceive(8888, "Two")).start();
        new Thread(new TalkSend(9999, "localhost", 7777)).start();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42448414/article/details/84948892