package ClientAndServer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient1 {
public static void main(String[] args) throws IOException{
InetAddress address = InetAddress.getByName("localhost");
int port = 8080;
byte[] data = "用户名:admin; 密码:123".getBytes();
//构建数据报,向服务器发送
DatagramPacket packet = new DatagramPacket(data, data.length,address,port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
//创建数据报,用于接收服务器端响应的数据
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
/*Constructs a DatagramPacket for receiving packets of length length.
The length argument must be less than or equal to buf.length.*/
socket.receive(packet2);
//读取数据
String reply = new String(data2,0,packet2.getLength());
System.out.println("我是客户端,服务器说: "+reply);
socket.close();
}
}
package ClientAndServer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer1 {
public static void main(String[] args) throws IOException{
DatagramSocket socket = new DatagramSocket(8080);
byte[] data = new byte[1024];//创建字节数组,指定接受的数据包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
System.out.println("****服务器端已启动,等待客户端发送数据");
socket.receive(packet);
String info = new String(data,0,packet.getLength());
System.out.println("我是服务器,客户端说: "+info);
//向客户端发送响应数据
//定义客户端的ip地址,端口号,数据
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "欢迎您! ".getBytes();
//创建数据报,包含响应的数据信息
DatagramPacket packet2 = new DatagramPacket(data2, data2.length,address,port);
//响应客户端
socket.send(packet2);
socket.close();
}
}