java 在java中通过UDP传输文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/798195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Transfer a file through UDP in java
提问by Diego Magalh?es
I have the following algorithm implemented in Java which uses TCP/IP:
我在使用 TCP/IP 的 Java 中实现了以下算法:
-Client request a file
-Server checks if the file exists
- if do: send contents of the file to the client
- if not: send "file not found" msg to the client
Now I`m having trouble implementing that using UDP Datapackets. Here is my code:
现在我在使用 UDP 数据包实现它时遇到了麻烦。这是我的代码:
CLIENT:
客户:
package br.com.redes.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import br.com.redes.configuration.CommonKeys;
public class TCPClient {
public static void exibirCabecalho(){
System.out.println("-------------------------");
System.out.println("TCP CLIENT");
System.out.println("-------------------------");
}
public static void main(String[] args) throws IOException {
TCPClient.exibirCabecalho();
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
if (args.length != 1){
System.out.println("O Programa deve ser chamado pelo nome + nome do servidor");
System.out.println("Ex: java TCPClient localhost");
System.exit(1);
}
System.out.println("Conectando ao servidor...");
try {
echoSocket = new Socket( args[0] , CommonKeys.PORTA_SERVIDOR);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket
.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Host n?o encontrado (" + args[0] + ")");
System.exit(1);
} catch (IOException e) {
System.err.println("Erro ao inicializar I/O para conexao");
System.exit(1);
}
System.out.println("Conectado, digite 'sair' sem as aspas para finalizar");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
String inputLine = in.readLine();
if (inputLine == null){
System.out.println("Servidor terminou a conex?o.");
System.out.println("Saindo...");
break;
}
System.out.println("Servidor: " + inputLine.replace("\n", "\n"));
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
SERVER:
服务器:
package br.com.redes.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import br.com.redes.configuration.CommonKeys;
public class TCPServer {
public static void exibirCabecalho(){
System.out.println("-------------------------");
System.out.println("TCP SERVER");
System.out.println("-------------------------");
}
public static void main(String[] args) throws IOException {
TCPServer.exibirCabecalho();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket( CommonKeys.PORTA_SERVIDOR );
} catch (IOException e) {
System.err.println("Erro ao iniciar servidor na porta: " + CommonKeys.PORTA_SERVIDOR );
System.exit(1);
}
System.out.println("Iniciando servidor na porta: " + CommonKeys.PORTA_SERVIDOR);
System.out.println("Aguardando cliente...");
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Erro ao receber conexoes.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
System.out.println("Cliente conectado, aguardando caminhos pra leitura...");
while ((inputLine = in.readLine()) != null) {
if (inputLine.equalsIgnoreCase("sair")) {
System.out.println("Sair detectado, fechando servidor...");
break;
}
outputLine = processar(inputLine);
out.println(outputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
private static String processar(String inputLine) {
final String ARQUIVO_NAO_ENCONTRADO = "arquivo n?o encontrado.";
final String ARQUIVO_IO = "erro ao ler arquivo.";
System.out.println("Procurando arquivo: " + inputLine);
File f = new File(inputLine);
try {
BufferedReader input = new BufferedReader(new FileReader(f));
String linha = null;
StringBuffer retorno = new StringBuffer();
retorno.append("\n");
retorno.append("Arquivo encontrado, lendo conteudo: " + inputLine + "\n");
while (( linha = input.readLine()) != null){
retorno.append(linha + "\n");
}
retorno.append("fim da leitura do arquivo\n");
return retorno.toString();
} catch (FileNotFoundException e) {
return ARQUIVO_NAO_ENCONTRADO;
} catch (IOException e) {
return ARQUIVO_IO;
}
}
}
回答by Gary
This certainly can be done using UDP datagrams. However, it is going to be a bit more difficult since UDP itself does not offer reliability or ordered packet delivery. Your application needs these features to deliver a file to the client. If you choose to use UDP, you will need to write extra code to accomplish this. Are you sure you really want to use UDP at all?
这当然可以使用 UDP 数据报来完成。然而,这会有点困难,因为 UDP 本身不提供可靠性或有序的数据包传输。您的应用程序需要这些功能来向客户端传送文件。如果您选择使用 UDP,则需要编写额外的代码来完成此操作。您确定真的要使用 UDP 吗?
If you choose TCP much like your example above, you won't need to worry about bytes getting there and in the correct order.
如果您像上面的示例一样选择 TCP,则无需担心字节会以正确的顺序到达那里。
I would begin by examining some examples at Sun Datagram Tutorial
我将首先检查Sun Datagram Tutorial 中的一些示例
回答by Daniel H.
I recommend to review the UDP protocol (RFC 768) and then use some base example. There are lots of example with UDP and Java (e.g. Java Tutorials -> Networking)
我建议查看 UDP 协议 ( RFC 768),然后使用一些基本示例。UDP 和 Java 有很多示例(例如Java 教程 -> 网络)
回答by Matthew Flaschen
I agree with Daniel H. You should also specifically look at java.net.DatagramSocket.
我同意 Daniel H。您还应该专门查看java.net.DatagramSocket。
回答by Brian Agnew
I'm wondering if you're getting confused between TCP and UDP ? Your code references TCP in its class names etc. but you're talking about UDP ? These are distinct protocols both using IP, but with distinct characteristics re. reliability/fragmentation/duplication etc.
我想知道您是否对 TCP 和 UDP 感到困惑?您的代码在其类名等中引用了 TCP,但您是在谈论 UDP 吗?这些是不同的协议,都使用 IP,但具有不同的特性。可靠性/碎片化/重复等。
See herefor differences.
请参阅此处了解差异。

