0

我的客户端可以正常将图像发送到服务器,但是当涉及到文本文件时,它们到达时是空的。任何想法我做错了什么?我真的很感激帮助,因为我已经尝试了很多天了。谢谢。

这是服务器代码:

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

1 回答 1

2
  1. BufferedReader在读取所有数据之前,您过早地关闭了服务器端。这基本上关闭了连接。
  2. 您不应使用ReaderWriter用于二进制图像数据等非字符流。并且您不应该BufferedReader与同一流的任何其他流包装器混合,因为它可能读取与填充缓冲区一样多的数据。
于 2012-06-12T11:48:26.630 回答