用udp通信实现发送端和接收端能传输文件的Java代码
时间: 2023-10-10 08:05:16 浏览: 114
以下是一个简单的基于UDP通信的文件传输Java代码示例:
发送端代码:
```java
import java.net.*;
import java.io.*;
public class FileSenderUDP {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
File file = new File("example.txt");
byte[] fileBytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(fileBytes);
DatagramPacket packet = new DatagramPacket(fileBytes, fileBytes.length, address, 12345);
socket.send(packet);
socket.close();
fis.close();
}
}
```
接收端代码:
```java
import java.net.*;
import java.io.*;
public class FileReceiverUDP {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(12345);
byte[] fileBytes = new byte[10000];
DatagramPacket packet = new DatagramPacket(fileBytes, fileBytes.length);
socket.receive(packet);
FileOutputStream fos = new FileOutputStream("received.txt");
fos.write(packet.getData());
socket.close();
fos.close();
}
}
```
需要注意的是,该示例只是一个简单的文件传输示例,实际应用中还需要对传输过程进行一些优化和异常处理。另外,由于UDP是无连接的协议,因此在实际应用中还需要设计一套可靠的传输机制来保证数据的可靠传输。
阅读全文