0

我有一个使用套接字传输文件的服务器和客户端连接,但是如果我希望能够在用户 JButton 操作时从客户端向服务器发送字符串,它会引发套接字关闭错误(因为我在Sender() 构造函数)。问题是,如果我不使用 dos.close(),客户端程序将不会运行/初始化 UI 框架。我究竟做错了什么?我需要能够在程序第一次运行时发送文件,然后再发送数据。

发件人:

public Sender(Socket socket) {

    List<File> files = new ArrayList<File>();
    files.add(new File(Directory.getDataPath("default.docx")));
    files.add(new File(Directory.getDataPath("database.db")));

    try {
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        DataOutputStream dos = new DataOutputStream(bos);
        dos.writeInt(files.size());
        for (File file : files) {
            dos.writeLong(file.length());
            dos.writeUTF(file.getName());
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            int theByte = 0;
            while ((theByte = bis.read()) != -1) { 
                bos.write(theByte);
            }
            bis.close();
        }
        dos.close(); // If this is disabled, the program won't work.
    } catch (Exception e) {
        e.printStackTrace();
    }
}

下载器:

public static byte[] document;

public Downloader(Socket socket) {
    try {
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis = new DataInputStream(bis);
        int filesCount = dis.readInt();
        for (int i = 0; i < filesCount; i++) {
            long size = dis.readLong();
            String fileName = dis.readUTF();
            if (fileName.equals("database.db")) {
                List<String> data = new ArrayList<String>();
                BufferedReader reader = new BufferedReader(new InputStreamReader(bis));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.trim().length() > 0) {
                        data.add(line);
                    }
                }
                reader.close();
                parse(data);
            } else if (fileName.equals("default.docx")) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                for (int x = 0; x < size; x++) {
                    bos.write(bis.read());
                }
                bos.close();
                document = bos.toByteArray();
            } 
        }
        //dis.close();
        } catch (Exception e) {
        e.printStackTrace();
    }
}
4

1 回答 1

0

您在客户端中的第一个接收循环在 EOS 处终止,这只发生在您关闭发送方中的套接字时,您不想这样做。在每种情况下,您都在文件之前发送长度,因此在两种情况下接收代码都应该如下所示:

long total = 0;
while ((total < size && (count = in.read(buffer, 0, size-total > buffer.length ? buffer.length : (int)(size-total))) > 0)
{
    total += count;
    out.write(buffer, 0, count);
}
out.close();

该循环从套接字输入流中准确读取字节并将其size写入.OutputStream outoutByteArrayOutputStream

于 2013-04-16T06:48:23.223 回答