这里我写的发送方和接收方都是平级的,不分客户端和服务端
发送方
public class Send {
public static void main(String[] args) throws Exception {
//端口号
int port=10086;
DatagramSocket socket = new
DatagramSocket();
String str = "I love you";//传输的消息
byte[] bytes = str.getBytes();
int length = bytes.length;
InetAddress address = InetAddress.getLocalHost();
//创建需要发送的数据报
DatagramPacket packet = new
DatagramPacket(bytes, length, address, port);
//DatagramSocket进行发送
socket.send(packet);
//关闭连接
socket.close();
}
}
接收方
public class Receive {
public static void main(String[] args)
throws Exception {
DatagramSocket socket = new
DatagramSocket(10086);
byte[] b = new byte[1024*1];
int length = b.length;
DatagramPacket packet = new
DatagramPacket(b, length);
//DatagramSocket接收消息
socket.receive(packet);
byte[] data = packet.getData();
String str=new String(data, 0, packet.getLength());
//定义一个输出流,将输出的内容存入本地硬盘
FileOutputStream outputStream = new
FileOutputStream("F:\\abc\\a.txt");
outputStream.write(data);
System.out.println(str);
outputStream.flush();
outputStream.close();
//关闭连接
socket.close();
}
}