The sender first reads a file locally, reads it in a byte array, and then constructs a DatagramPacket and sends it to the receiver through the DatagramSocket object.
The receiver is stored locally. The two processes are opposite.
Example: transfer a picture. Size: 1525 bytes.
Code:
sender:
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class SendFile implements Runnable{
@Override
public void run() {
send();
}
public void send(){
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\...\\test.png"));
int length=bis.available();
DatagramSocket ds = new DatagramSocket();
byte[] buf = new byte[length];
bis.read(buf);
DatagramPacket dp = new DatagramPacket(buf,buf.length, InetAddress.getByName("127.0.0.1"),10001);
ds.send(dp);
ds.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("信息已发送!");
}
}
receiver:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveFile implements Runnable{
@Override
public void run() {
receive();
}
public void receive(){
System.out.println("等待信息...");
try {
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(
"D:\\...\\testtttt.png"));
DatagramSocket ds = new DatagramSocket(10001);
byte[] buf = new byte[1024]; // 小于文件大小
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
ds.close();
fos.write(dp.getData());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Main method:
public class Main {
public static void main(String[] args) {
new Thread(new ReceiveFile()).start();
new Thread(new SendFile()).start();
}
}
The byte array used for receiving is smaller than the size of my file.
The result of this execution is: (the right side is the sent file, the left is the received file)
Change the receiver's code:
byte[] buf = new byte[1024*2];
The picture is complete: (the file name is the same, the old picture is directly overwritten)