【问题标题】:Transfer binary file by byte array using TCP in java在java中使用TCP按字节数组传输二进制文件
【发布时间】:2012-02-06 07:51:51
【问题描述】:

我正在尝试一次将二进制文件从服务器传输到客户端一个字节块。但是,我遇到了传输 8kb 时卡住的问题。该文件通常大于 1mb,字节数组的大小为 1024。我相信它与我的 while 循环有关,因为它不会关闭我的连接。有什么帮助吗?谢谢

客户

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

public class FileClient {

    public static void main(String[] argv) throws IOException {
        Socket sock = new Socket("localhost", 4444);
        InputStream is = null;
        FileOutputStream fos = null;

        byte[] mybytearray = new byte[1024];
        try {
            is = sock.getInputStream();
            fos = new FileOutputStream("myfile.pdf");

            int count;
            while ((count = is.read(mybytearray)) >= 0) {
                fos.write(mybytearray, 0, count);
            }
        } finally {
            fos.close();
            is.close();
            sock.close();
        }
    }
}

服务器

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

public class FileServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servsock = new ServerSocket(4444);
        File myFile = new File("myfile.pdf");
        FileInputStream fis = null;
        OutputStream os = null;
        while (true) {
            Socket sock = servsock.accept();
            try {
            byte[] mybytearray = new byte[1024];
            fis = new FileInputStream(myFile);
            os = sock.getOutputStream();

            int count;
            while ((count = fis.read(mybytearray)) >= 0) {
                os.write(mybytearray, 0, count);

            }
            os.flush();
            } finally {
            fis.close();
            os.close();
            sock.close();

            System.out.println("Socket closed");
            }
        }
    }
}

【问题讨论】:

    标签: java sockets tcp filestream


    【解决方案1】:

    您的循环应该检查count >= 0 而不是count > 0,并且流和套接字应该在finally 块中关闭。除此之外,代码对我来说看起来不错。

    “传输 8kb 时卡住”是什么意思?有什么异常吗?

    【讨论】:

    • 我更改了计数并添加了 finally 块,但问题仍然存在。我所说的卡住的意思是它没有到​​达 finally 块。它只复制和写入大约 8kb 的数据,而且它只是停止
    • finally 块应该在 while 循环之外。并且您应该通过捕获关闭调用本身引发的 IOException 来确保每个流都已关闭。哪个档位?客户端还是服务器?
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2020-06-26
    • 2019-10-29
    • 2012-01-12
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多