使用java中的套接字转移到客户端时,word文件会损坏

时间:2016-07-01 10:29:05

标签: java sockets client-server

此代码传输除officex文件之外的所有文件,如docx和pdf。需要修复。正在传输大尺寸的文件并且没有损坏,但问题仍然存在,只有word或pdf或powerpoint或excel文件。

这是客户端代码

FileInputStream reader= new FileInputStream(new File(path));
byte[] buffer=new byte[512];
int count=0;
dataSendingStream.writeUTF("upload");

System.out.println(filename);
dataSendingStream.writeUTF(filename);

dataSendingStream.writeInt(count);
System.out.println(count);
do
{
    count=reader.read(buffer);
    dataSendingStream.writeInt(count);
    if(count!=-1)
        dataSendingStream.write(buffer);
    if(count!=-1)
    {
        for(int i=0;i<512;i++)
        {
            System.out.println("item "+i+" in buffer is     "+Byte.toString(buffer[i]));
        }
    }

    System.out.println(buffer);
    System.out.println(count);
}
while(count!=-1);

这是服务器端代码

String filename=fins.readUTF();
File file=new File("E:\\repository\\"+filename);
BufferedOutputStream writer=new BufferedOutputStream(new FileOutputStream(file));
int count=fins.readInt();
byte[] buffer=new byte[512];
while(count!=-1)
{
    System.out.println(count);
    count=fins.readInt();
    if(count==-1)
        break;
    fins.read(buffer);
    for(int i=0;i<512;i++)
        System.out.println("item "+i+" in buffer is "+Byte.toString(buffer[i]));
    writer.write(buffer);
}

writer.flush();
System.out.println("file written");
writer.close();
System.out.println("file recieved");

0 个答案:

没有答案