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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用UDP在服务器和客户端之间传输文件(.png,.text)相关的知识,希望对你有一定的参考价值。

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

服务器端:

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("
Running...
");

            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("
");
            int c=0;

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

            sb.append(c+ " files found.

");

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

            sb.append("
Enter 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
");
        }

    }
}

客户端:

import java.io.*;
import java.net.*;
import java.util.Scanner;

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

        DatagramSocket socket = null;
        DatagramPacket inPacket = null;
        DatagramPacket outPacket = null;
        byte[] inBuf, outBuf;
        final int PORT = 50000;
        String msg = null;
        Scanner src = new Scanner(System.in);


        try
        {
                InetAddress address = InetAddress.getByName("127.0.0.1");
                socket = new DatagramSocket();

                msg = "";
                outBuf =msg.getBytes();
                outPacket = new DatagramPacket(outBuf, 0, outBuf.length,address,PORT);
                socket.send(outPacket);

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

                String data = new String(inPacket.getData(), 0, inPacket.getLength());
                //Print file list
                System.out.println(data);

                //Send file name
                String filename = src.nextLine();
                outBuf = filename.getBytes();
                outPacket = new DatagramPacket(outBuf, 0, outBuf.length, address, PORT);
                socket.send(outPacket);

                //Receive file
                inBuf = new byte[100000];
                inPacket = new DatagramPacket(inBuf, inBuf.length);
                socket.receive(inPacket);

                data = new String(inPacket.getData(), 0, inPacket.getLength());
                if(data.endsWith("ERROR"))
                {
                        System.out.println("File doesn't exists.
");
                        socket.close();
                }

                else
                {
                    try
                    {
                            BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
                            pw.write(data);
                            //Force write buffer to Fİle
                            pw.close();

                            System.out.println("File Write Succesful. Closing Socket");
                            socket.close();

                    } catch (Exception ioe) {
                        System.out.println("File Error
");
                        socket.close();
                    }
                }

        } catch (Exception e) {
            System.out.println("
Network Error. Try Again Later. 
");
        }

    }
}
答案

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

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

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

以上是关于使用UDP在服务器和客户端之间传输文件(.png,.text)的主要内容,如果未能解决你的问题,请参考以下文章

TFTP 简单文件传输协议

网络协议TFTP

TFTP服务[精简版]:简单文件传输协议

netcat——文件传输

如何使用udp将大文件从服务器传输到客户端

Socket与Http区别、优缺点及应用场景