java - 在java中通过UDP传输文件

标签 java sockets udp tcp

我在使用 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

现在我在使用 UDP 数据包实现它时遇到了麻烦。这是我的代码:


客户:

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();
    }

}

服务器:

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;
        }
    }
}

最佳答案

这当然可以使用 UDP 数据报来完成。然而,这会有点困难,因为 UDP 本身不提供可靠性或有序的数据包传送。您的应用程序需要这些功能才能将文件传送给客户端。如果您选择使用 UDP,您将需要编写额外的代码来完成此操作。您确定真的要使用 UDP 吗?

如果您像上面的示例一样选择 TCP,则无需担心字节以正确的顺序到达那里。

我将从检查 Sun Datagram Tutorial 上的一些示例开始

关于java - 在java中通过UDP传输文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/798195/

相关文章:

networking - 谁是 UDP 中的服务器,谁是客户端?

java - 无法从 Controller 中的请求获取 token

docker - 使用卷时无法在主机上使用 mysql 套接字

c# - 使用 Socket.SendToAsync() 时如何指定要发送的字节数?

c# - 有谁知道我在哪里可以找到通用 Windows 专用网络(客户端和服务器)代码示例?

php - 当使用 netcat 作为客户端发送文件或管道输出时,如何避免 netcat 阻塞?

java - 如何将响应与 Netty 中的请求关联起来?

java - HTML CDATA 问题

java - spring auth错误没有AuthenticationProvider

java - 在java中写入XML文件时出错