我必须使用UDP将任何大小的文件从客户端发送到服务器。我以字节数组发送数据报。我拆分文件并发送数据报。我知道服务器接收数据报但我的问题是如何将数据报再次放入文件中。这是我的客户端代码(我只是将代码拆分并发送文件,我将JavaFX用于客户端)。 提前谢谢大家。
private void sendFile(ActionEvent event) {
ArrayList<byte[]> listDatagrams;
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String serverName = "localhost";
InetAddress IPserver;
int serverPort = 6789;
byte[] data;
DatagramPacket request;
IPservidor = InetAddress.getByName(serverName);
data = Files.readAllBytes(file.toPath());
listDatagrams = splitFile(data);
for(byte[] datagrama : listDatagrams){
request= new DatagramPacket(datagrama, datagrama.length, IPserver, serverPort );
socket.send(request);
}
try {
fileOuputStream.write(respuesta.getData());
} finally {
fileOuputStream.close();
}
} catch (SocketException e) {
System.out.println("SocketException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
} finally {
if (socket != null) {
socket.close();
}
}
}
这是我用来拆分文件的方法:
public ArrayList<byte []> splitFile(byte[] file){
ArrayList<byte[]> data = new ArrayList<>();
double nPartitions;
byte[] partition= new byte[MAX];
if(file.length>MAX){
nPartitions =Math.ceil(file.length/MAX);
for(int i=0; i<=nPartitions; i++)
for(int j=0; j<MAX; j++){
if(i==0){
if(j==file.length-1)
break;
partition[j]=file[j];
}else if(i==1){
if((j+MAX)==file.length-1){
break;
}else{
partition[j]=file[(j+MAX)];
}
}else{
if((j+MAX)>=file.length-1)
break;
partition[j]=file[(i*(MAX+1))+j];
}
}
data.add(partition);
}
}
return data;
}
服务器的代码:
public static void main(String args[]) {
DatagramSocket socket = null;
ArrayList<DatagramPacket> data= new ArrayList<>();
try {
int serverPort= 6789;
socket = new DatagramSocket(serverPort);
byte[] buffer;
buffer = new byte[5000];
while (true) {
DatagramPacket request;
request= new DatagramPacket(buffer, buffer.length);
socket.receive(request);
//I add the datagramas to an array list but I am not sure how to re arrenge them into a File. The server should always be on and be able to receive a second file if I want to
data.add(request);
}
} catch (SocketException e) {
System.out.println("SocketException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
} finally {
if (socket != null) {
socket.close();
}
}
}
注意:我知道TCP更好,但这适用于学校