public class UDPClient {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 8888;
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);
socket.receive(packet2);
String reply = new String(data2,0,packet2.getLength());
System.out.println("我是客户端,服务器说:"+reply);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(8888);
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);
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "欢迎您".getBytes();
DatagramPacket pack2 = new DatagramPacket(data2, data2.length,address,port);
socket.send(pack2);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}