文件在套接字编程中被破坏

时间:2017-12-09 09:20:51

标签: java sockets serversocket

我正在尝试将文件从客户端发送到服务器端。这里,WritableGUI是一个在文本区域中显示文件名的接口。文件已传输到服务器但已损坏。有时传输的文件大小是正确的,但有时它显示文件大小为0 kb。我的代码怎么了?

客户端:

public class FileClient {

    private Socket s;
    private String fileName;
    private long fileLength;

    public FileClient(String host, int port, String file, String fileName, long FileLength) {
        this.fileName = fileName;
        this.fileLength = FileLength;
        try {
            s = new Socket(host, port);
            sendFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendFile(String file) throws IOException {
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        dos.writeUTF(fileName);
        dos.writeLong(fileLength);
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
        fis.close();
        dos.close();
    }
}       

服务器端:

public class FileServer extends Thread {

    ServerSocket server;
    int port = 8877;
    WritableGUI gui;

    public FileServer(WritableGUI gui, int SOCKET_PORT) throws IOException {
        this.port = SOCKET_PORT;
        this.gui = gui;

        try {
            server = new ServerSocket(port);
        } catch (IOException ex) {
            Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        while (true) {
            try {
                Socket clientSock = server.accept();
                saveFile(clientSock);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveFile(Socket clientSock) throws IOException {
        DataInputStream dis = new DataInputStream(clientSock.getInputStream());
        FileOutputStream fos = new FileOutputStream(dis.readUTF());
        byte[] buffer = new byte[1024];

        gui.write("File Received: " + dis.readUTF());

        long filesize = dis.readLong(); // read file size in separate msg
        int read = 0;
        int totalRead = 0;
        int remaining = (int) filesize;
        while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 0) {
            totalRead += read;
            remaining -= read;
            System.out.println("read " + totalRead + " bytes.");
            fos.write(buffer, 0, read);
        }
        dis.close();
        fos.close();
    }
}

1 个答案:

答案 0 :(得分:0)

while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }
像往常一样。错误的复制循环。试试这个:

int count;
while ((count = fis.read(buffer)) > 0) {
        dos.write(buffer, 0, count);
    }

并且好好思考为什么。