连接时接收文件超时

Receiving file on connection timed out

我制作了一个向客户端发送文本文件的服务器 (Android),我只在连接超时时才获取该文件。

为什么 "connection timed out" 首先发生?而且,接收文件 (1MB) 大约需要 1 分钟。

服务器:

    FileInputStream fis = new FileInputStream(
                                        new File("123.txt");
                                BufferedInputStream bis = new BufferedInputStream(fis);
                                DataInputStream dis = new DataInputStream(bis);

                                byte[] mybytearray = new byte[8192];

                                OutputStream os;
                                try {
                                    os = clientSocket.getOutputStream();
                                    DataOutputStream dos = new DataOutputStream(os);
                                    int read;

                                    while ((read = dis.read(mybytearray)) > 0) {
                                        dos.write(mybytearray, 0, read);

                                    }

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

客户:

InputStream in;
                                    int Size = 0;

                                    try {
                                        Size = clientSocket.getReceiveBufferSize();
                                        in = clientSocket.getInputStream();
                                        DataInputStream dis = new DataInputStream(in);
                                        byte[] buffer = new byte[Size];
                                        int read;

                                        while ((read = dis.read(buffer)) > 0) {
                                            fos.write(buffer, 0, read);
                                        }

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }

知道如何解决这个问题吗?

您没有在服务器端关闭流。所以没有人知道这是流的结尾,等待一直持续到超时。像这样添加 close() :

 os = clientSocket.getOutputStream();
 DataOutputStream dos = new DataOutputStream(os);
 int read;

  while ((read = dis.read(mybytearray)) > 0) {
       dos.write(mybytearray, 0, read);
  }
  os.close();

此外,在客户端,您应该期望零输入。它可以用于慢速连接。只有 -1 表示连接已关闭。像这样更改代码:

while ((read = dis.read(buffer)) > -1)