UDP

时间:2021-02-22 05:17:18

我们通过以下代码来连了解以下UPD

首先我们先创建Server类

package cn.a.qwe;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException; public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket sockets=new DatagramSocket(50000); byte[] bytes = new byte[1024]; DatagramPacket packet = new DatagramPacket(bytes, 0,bytes.length); sockets.receive(packet); byte[] data = packet.getData(); String temp = new String(data,0,data.length);
System.out.println(temp);
}
}

紧接着我们来创建一个Client类

package cn.a.qwe;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException; public class Client {
public static void main(String[] args) throws Exception {
String word="开启成功";
byte[] bytes=word.getBytes();
DatagramSocket client = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("localhost"), 50000);
client.send(packet);
}
}

启动之后我们可以看到当Client运行时,我们可以看到Server类会有"开启成功"的字段输出