[Java] 纯文本查看 复制代码
public class UDP_Send {
public static void main(String[] args) throws IOException {
// 创建输入流,将客户端本地文件读到内存
FileInputStream in = new FileInputStream("C:\\Users\\Administrator\\Desktop\\b.png");
// 创建packet包装数据
byte[] b = new byte[1024];
while (true) {
int len = in.read(b);
if (len != -1) {
// 使用客户端随机端口向服务器传输信息
DatagramSocket ds_send = new DatagramSocket();
DatagramPacket dp_send = new DatagramPacket(b, len, InetAddress.getLocalHost(), 45667);
// 向服务器发送数据包
ds_send.send(dp_send);
ds_send.close();
}else {
// 向服务器传入结束标签
DatagramSocket ds_send = new DatagramSocket();
byte[] end = "end".getBytes();
DatagramPacket dp_send = new DatagramPacket(end, end.length, InetAddress.getLocalHost(), 45667);
ds_send.send(dp_send);
ds_send.close();
break;
}
}
in.close();
System.out.println("正在上传....");
// 创建DatagramSocket接收服务器反馈<接收端口46667>
DatagramSocket ds_receive = new DatagramSocket(46667);
byte[] message = new byte[1024];
DatagramPacket dp_receive = new DatagramPacket(message, message.length);
// 接收响应
ds_receive.receive(dp_receive);
// 解析到控制台
byte[] result = dp_receive.getData();
System.out.println(new String(result));
// 关流
ds_receive.close();
}
}
[Java] 纯文本查看 复制代码
public class UDP_Receive {
public static void main(String[] args) throws SocketException, IOException {
System.out.println("服务器开启.....");
// 创建输出流,将内存文件保存到服务器硬盘
FileOutputStream out = new FileOutputStream(System.currentTimeMillis() + ".png");
// 创建DatagramSocket指定接收端口
DatagramSocket ds_receive = new DatagramSocket(45667);
byte[] receive = new byte[1024];
DatagramPacket dp_receive = new DatagramPacket(receive, receive.length);
System.out.println("等待上传...");
// 接收客户端数据,遇到结束标签退出
while (true) {
ds_receive.receive(dp_receive);//最后一步读到这里停止了
byte[] b = dp_receive.getData();
String data = new String(b);
// 判断是否结束
if (data.trim().endsWith("end")) {
ds_receive.close();
break;
}
// System.out.println(data);不写这句话正常
// 文件写到硬盘
out.write(b);
}
// 关闭流
out.close();
ds_receive.close();
System.out.println("保存成功!");
// 向客户端发送响应信息
DatagramSocket ds_send = new DatagramSocket();
byte[] message = "上传成功!".getBytes();
DatagramPacket dp_send = new DatagramPacket(message, message.length, InetAddress.getLocalHost(), 46667);
ds_send.send(dp_send);
// 关流
ds_send.close();
}
}