没有客户端和服务端这一说法
package Internet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
// UDP:类似发短信
// 发送端
public class Test09_UDP_User1 {
public static void main(String[] args) throws Exception {
// 1.建一个Socket
DatagramSocket socket = new DatagramSocket();
// 2.建一个包裹
String msg="msg";
InetAddress local = InetAddress.getByName("127.0.0.1");
int port=8888;
// 建一个包裹的主要部分
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.length(),local,port);
// 3.发送包裹
socket.send(packet);
// 4.关闭
socket.close();
}
}
//////////////////////////////////
package Internet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收端
public class Test09_UDP_User2 {
public static void main(String[] args) throws Exception {
// 1.建一个Socket
DatagramSocket socket = new DatagramSocket(8888);
// 2.建一个新的包裹,接收传输过来的东西 packet2装下packet
byte[] buffer = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(buffer,0,buffer.length);
// 3.接收发过来的包裹 packet2装下packet
socket.receive(packet2);
// 验证包裹
System.out.println(new String(packet2.getData(),0,packet2.getLength()));
// 4.关闭
socket.close();
}
}
标签:DatagramSocket,UDP,java,packet2,发送,消息,new,import,net
From: https://www.cnblogs.com/zhanjianhai/p/17689940.html