UDP实现通信

UDP实现通信

1.创建连接 DatagramSocket

2.构建包 DatagramPacket

3.发送包 .send() 或接收包.receive()

发送方

package com.example.network;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        // 创建连接

        DatagramSocket socket = new DatagramSocket();

        // 构建包
        byte[] msg = new byte[1024];
        msg = "服务器,你好!".getBytes(StandardCharsets.UTF_8);
        int port = 9090;
        DatagramPacket packet = new DatagramPacket(msg, 0, msg.length, InetAddress.getByName("localhost"), port);

        // 发送包
        socket.send(packet);

        // 关闭资源
        socket.close();
    }
}

接收方

package com.example.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServiceDemo01 {
    public static void main(String[] args) throws IOException {
        // 建立连接
        DatagramSocket socket = new DatagramSocket(9090);

        //接收数据
        byte[] msg = new byte[1024];
        DatagramPacket packet = new DatagramPacket(msg, 0, msg.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), 0, packet.getLength()));

        // 关闭资源
        socket.close();
    }
}
posted @ 2021-11-18 15:47  Oh,mydream!  阅读(154)  评论(0编辑  收藏  举报