//客户端
package test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
System.out.println("-------客户端---------");
try {
// 1.创建DatagramSocket套接字对象
DatagramSocket ds = new DatagramSocket(1212);
// 2.要把传送的数据,转换成二进制数据----byte类型数组
String str = "小姐姐谈恋爱么?我是大叔音哦";
byte b[] = str.getBytes();
// 3.把二进制数据封装进数据包中,并指定要发送的地址和端口号
DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 3434);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//服务端
package test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Server {
public static void main(String[] args) {
System.out.println("-----------服务器-----------");
try {
// 1.创建DatagramSocket套接字对象
DatagramSocket ds = new DatagramSocket(3434);
// 2.创建byte类型数组,并指定长度
byte b[] = new byte[1024];
// 3.创建数据包
DatagramPacket dp = new DatagramPacket(b, b.length);
// 4.接收数据包
ds.receive(dp);
// 5.把字节数组转换成String,并输出
System.out.println("客户" + new String(b));
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}