[Java网络编程基础]UDP发送和接收数据

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java网络编程基础]UDP发送和接收数据相关的知识,希望对你有一定的参考价值。

在这里插入图片描述

代码如下:

package InetAddressPack;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class SendDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();

        byte[] bys = "hellp,udp,我来了".getBytes();
        int len = bys.length;
        InetAddress address = InetAddress.getByName("192.168.1.123");
        int port = 10086;

        DatagramPacket dp = new DatagramPacket(bys,len,address,port);

        ds.send(dp);

        ds.close();

    }
}
package InetAddressPack;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class SendDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();

        byte[] bys = "hellp,udp,我来了".getBytes();
//        int len = bys.length;
//        InetAddress address = InetAddress.getByName("192.168.1.123");
//        int port = 10086;

        DatagramPacket dp = new DatagramPacket(bys, bys.length,InetAddress.getByName("192.168.1.123"),10086);

        ds.send(dp);

        ds.close();

    }

}

在这里插入图片描述

代码如下:

package InetAddressPack;

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

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10086);

        byte[] bys = new byte[1024];

        DatagramPacket dp = new DatagramPacket(bys,bys.length);

        ds.receive(dp);

        byte[] datas = dp.getData();
        int len = dp.getLength();
        String dataString = new String(datas,0,len);
        System.out.println("数据是"+dataString);

        ds.close();

    }

}

package InetAddressPack;

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

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10086);

        byte[] bys = new byte[1024];

        DatagramPacket dp = new DatagramPacket(bys,bys.length);

        ds.receive(dp);

        byte[] datas = dp.getData();
        int len = dp.getLength();
//        String dataString = new String(datas,0,len);
//        System.out.println("数据是"+dataString);
        
        System.out.println("数据是: "+new String(dp.getData(),0,dp.getLength()));

        ds.close();

    }

}

以上是关于[Java网络编程基础]UDP发送和接收数据的主要内容,如果未能解决你的问题,请参考以下文章

Java 网络编程UDP协议之发送数据和接收数据的详解

java基础——UDP实现dos聊天室案例

java-udp编程

Java编程基础之网络编程

JAVA-基础-UDP和TCP通信

Java:通过 TCP 发送/接收数据并从 UDP 接收图像