package com.kuang.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//2023.3.6 UDP通信方式实现发送消息 ----不需要连接服务器
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//1.建立一个Socket
DatagramSocket socket= new DatagramSocket();
//2.建个包 发送消息
String msg = "你好啊,服务器!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//数据,数据的长度起始,要发送给谁
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length,localhost,port);
//3.发送包
socket.send(packet);
//4.关闭流
socket.close();
}
}
//
package com.kuang.lesson03;标签:DatagramSocket,03,DatagramPacket,Java,socket,java,--,packet,new From: https://www.cnblogs.com/CaiDingChao/p/17717659.html
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//2023.3.6 UDP 服务器端 ---还是要等待客户端的连接
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接受数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//关闭连接
socket.close();
}
}