发送文件名然后文件本身

时间:2012-06-11 22:54:20

标签: java file sockets

我想让我的服务器能够获取将发送给它的文件的名称,然后在获取该文件后,它可以将其保存在具有正确名称的新位置。

这是服务器代码:

class TheServer {

    public void setUp() throws IOException { // this method is called from Main class.
        ServerSocket serverSocket = new ServerSocket(1991);
        System.out.println("Server setup and listening...");
        Socket connection = serverSocket.accept();
        System.out.println("Client connect");
        System.out.println("Socket is closed = " + serverSocket.isClosed());



        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String str = rd.readLine();
        System.out.println("Recieved: " + str);
        rd.close();



        InputStream is = connection.getInputStream();

        int bufferSize = connection.getReceiveBufferSize();

        FileOutputStream fos = new FileOutputStream("C:/" + str);
        BufferedOutputStream bos = new BufferedOutputStream(fos);


        byte[] bytes = new byte[bufferSize];

        int count;

        while ((count = is.read(bytes)) > 0) {
            bos.write(bytes, 0, count);
        }

        bos.flush();
        bos.close();
        is.close();
        connection.close();
        serverSocket.close();


    }
}

这是客户端代码:

public class TheClient {

    public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
        Socket socket = null;
        String host = "127.0.0.1";

        socket = new Socket(host, 1991);

        // Get the size of the file
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large.");
        }

        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        wr.write(file.getName());
        wr.flush();

        byte[] bytes = new byte[(int) length];
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

        int count;

        while ((count = bis.read(bytes)) > 0) {
            out.write(bytes, 0, count);
        }


        out.flush();
        out.close();
        fis.close();
        bis.close();
        socket.close();
    }
}

我对自己进行了一些测试,似乎我的客户端正在发送文件的名称,但不知何故服务器错了。例如,如果我的客户端告诉该文件的名称是“test.txt”,我的服务器就会获得它,例如“test.txt'--------------------”或“test.txtPK”。我无法理解为什么它不能正常得名。谁知道为什么会这样?或者有更简单的方法吗?我的第二个问题是,我怎样才能在本地主机中使用它,而不是在任何地方?我尝试将主机更改为我的IP地址,但它没有用。感谢。

1 个答案:

答案 0 :(得分:3)

您永远不会在文件名后发送行尾。因此,当服务器使用readLine()进行读取时,它将读取所有字符,直到找到可能位于文件内容某处的第一行结束。有时它在'-----'之后,有时在'PK'之后。