使用java socket发送文件

时间:2017-05-03 07:54:29

标签: java sockets

我在这里发送来自两个java应用程序的文件,服务器的源代码和客户端

public class FileClient {

    private Socket s;

    public FileClient(String host, int port, String file) {
        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[4096];

        while ((fis.read(buffer) > 0)) {
            dos.write(buffer);
        }

        fis.close();
        dos.close();    
    }

    public static void main(String[] args) {
        FileClient fc = new FileClient("192.168.0.167", 1988, "C:/Users/mhattabi/Desktop/fileData.txt");
    }

}

这里是服务器的源代码

public class FileServer extends Thread {

    private ServerSocket ss;

    public FileServer(int port) {
        try {
            ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                Socket clientSock = ss.accept();
                saveFile(clientSock);

            //  ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void saveFile(Socket clientSock) throws IOException {
        DataInputStream dis = new DataInputStream(clientSock.getInputStream());
        FileOutputStream fos = new FileOutputStream("fileData.txt");
        byte[] buffer = new byte[4096];

        int filesize = 15123; // Send file size in separate msg
        int read = 0;
        int totalRead = 0;
        int remaining = filesize;
        while((read = dis.read(buffer)) > 0) {
            totalRead += read;
            System.out.println("read " + totalRead + " bytes.");
            fos.write(buffer, 0, read);
        }

        fos.close();
        dis.close();
    }

    public static void main(String[] args) {
        FileServer fs = new FileServer(1988);
        fs.start();
    }

}

在服务器中我收到文件但有额外字符的问题看起来像这样。任何帮助将不胜感激谢谢 enter image description here

2 个答案:

答案 0 :(得分:0)

常见问题。

while ((fis.read(buffer) > 0)) {
    dos.write(buffer);
}

您忽略了读取返回的计数,并假设它填充了缓冲区。它应该是:

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

奇怪的是,你在服务器中拥有这个权利。注意:这里不需要DataOutputStream

答案 1 :(得分:-1)

 byte[] buffer = new byte[4096];

我认为"额外的角色"来自这个地方;每次写4096字节 ,最后一次发生不到4096字节。然后你得到额外的字符