使用UDP在服务器和客户端之间传输文件(.png,.txt)

时间:2018-01-04 21:46:04

标签: java server ftp udp client

我为客户端编写了一个服务器和客户端连接到服务器,并从服务器的目录中选择一个数据来传输带有UDP协议的数据,但问题是,它只适用于.txt文件,它不是&对于.png文件以及.txt文件中的输出文件与原始文件不同,输出文件与单词之间的行不相同,所有单词并排打印而不是逐行打印。我该如何解决这个问题?

服务器端:

def __init__(self, **kwargs):
    super(Easy_Level_Addition, self).__init__(**kwargs)
    self.correct_answers = []
    self.incorrect_answers = []
    self.questions_count = []

客户方:

import java.io.*;
import java.net.*;

public class FTPServer {
    public static void main(String[] args) 
    {

        DatagramSocket socket = null;
        DatagramPacket inPacket = null;
        DatagramPacket outPacket = null;
        byte[] inBuf, outBuf;
        String msg;
        final int PORT = 50000;

        try
        {
            socket = new DatagramSocket(PORT);
            while(true) 
            {
            System.out.println("\nRunning...\n");

            inBuf = new byte[1000];
            inPacket = new DatagramPacket(inBuf, inBuf.length);
            socket.receive(inPacket);

            int source_port=inPacket.getPort();
            InetAddress source_address = inPacket.getAddress();
            msg = new String(inPacket.getData(), 0, inPacket.getLength());
            System.out.println("CLient: " + source_address + ":" + source_port);

            String dirname  = "/home/erke/Desktop/data";
            File f1 = new File(dirname);
            File fl[] = f1.listFiles();

            StringBuilder sb = new StringBuilder("\n");
            int c=0;

            for(int i = 0;i<fl.length;i++)
            {
                if(fl[i].canRead())
                    c++;
            }

            sb.append(c+ " files found.\n\n");

            for(int i=0; i<fl.length;i++)
                    sb.append(fl[i].getName()+ " " + fl[i].length()+ " Bytes\n");

            sb.append("\nEnter file name to Download: ");
            outBuf = (sb.toString()).getBytes();
            outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
            socket.send(outPacket);

            inBuf = new byte[1000];
            inPacket = new DatagramPacket(inBuf, inBuf.length);
            socket.receive(inPacket);
            String filename = new String(inPacket.getData(), 0, inPacket.getLength());

            System.out.println("Requested File: " + filename);

            boolean flis = false;
            int index =-1;
            sb = new StringBuilder("");
            for(int i=0;i<fl.length;i++) 
            {
                    if(((fl[i].getName()).toString()).equalsIgnoreCase(filename))
                    {
                        index = i;
                        flis = true;

                    }
            }

            if(!flis) 
            {
                    System.out.println("ERROR");
                    sb.append("ERROR");
                    outBuf = (sb.toString()).getBytes();
                    outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
                    socket.send(outPacket);
            }
            else
            {
                try
                {
                        //File send
                        File ff=new File(fl[index].getAbsolutePath());
                        FileReader fr = new FileReader(ff);
                        BufferedReader brf = new BufferedReader(fr);
                        String s = null;
                        sb=new StringBuilder();

                        while((s=brf.readLine())!=null)
                        {
                            sb.append(s);
                        }

                        if(brf.readLine()==null)
                                System.out.println("File Read Succesfull, CLosing Socket");

                        outBuf=new byte[100000];
                        outBuf = (sb.toString()).getBytes();
                        outPacket = new DatagramPacket(outBuf, 0, outBuf.length,source_address, source_port);
                        socket.send(outPacket);

                } catch (Exception ioe) {
                    System.out.println(ioe);
                }

            }
            }


        } catch (Exception e){
            System.out.println("Error\n");
        }

    }
}

1 个答案:

答案 0 :(得分:1)

在您的代码中,您使用String在客户端和服务器中存储文件数据。为了能够传输除文本文件之外的任何文件,在服务器中应该有byte[]缓冲区而不是String,并使用它来加载文件内容。您可以使用名称以InputStream结尾的类来执行此操作。执行此操作后,通过网络发送这些字节。客户也一样。

InputStreamOutputStream用于直接从文件读取\ write字节,而ReaderWriter类专门用于处理文本文件。你不能用这些类读取\ write bytes,它们只能用于字符和字符串。您仍然可以传输文本文件,因为它们也只是一个字节数组。

如果你想传输你的文件而不丢失数据包,你应该使用TCP,而UDP往往会这样做,因为它没有机制来确保数据包像TCP一样安全地传送到目的地。