我在用socket上传文件时,发现传过去的文件要大于原文件,比例大概是1/15,连接没有问题,不用byte数组没有问题,但是速度太慢,源码如下:
这是客户端;try{
Socket client = new Socket("192.168.1.14",1099) ;
if(client.isConnected())
{
FileInputStream fis = new FileInputStream(new File("zuma.zip"));
CheckedOutputStream cos =  new CheckedOutputStream(client.getOutputStream(), new Adler32());
GZIPOutputStream gos = new GZIPOutputStream(cos);
byte []bit = new byte[100]; 
while(fis.read(bit) != -1)
{
gos.write(bit);
}

fis.close();
gos.close();
}
}catch(Exception ex)
{
ex.printStackTrace();
}这是服务器端:
                        client = ss.accept();
System.out.println(client.toString());

FileOutputStream fos = new FileOutputStream(new File("zuma.zip"));
CheckedInputStream cis = new CheckedInputStream(client.getInputStream(),new Adler32());
GZIPInputStream gis = new GZIPInputStream(cis);
int i = 0;
while((i = gis.read()) != -1)
{
fos.write(i);
fos.flush();

}
System.out.println("ok");

gis.close();
fos.close();
Thread.sleep(10);
client.close();
}catch(Exception ex)
{

}

解决方案 »

  1.   

    对不起,拷错了,客户端:
    try{
    Socket client = new Socket("192.168.1.14",1099) ;
    if(client.isConnected())
    {
    FileInputStream fis = new FileInputStream(new File("zuma.zip"));
    CheckedOutputStream cos =  new CheckedOutputStream(client.getOutputStream(), new Adler32());
    GZIPOutputStream gos = new GZIPOutputStream(cos);
    byte []bit = new byte[100]; 
    while(fis.read(bit) != -1)
    {
    gos.write(bit);
    gos.flush();
    }

    fis.close();
    gos.close();
    }
    }catch(Exception ex)
    {
    ex.printStackTrace();
    }
    服务器端:try{
    client = ss.accept();
    System.out.println(client.toString());

    FileOutputStream fos = new FileOutputStream(new File("zuma.zip"));
    CheckedInputStream cis = new CheckedInputStream(client.getInputStream(),new Adler32());
    GZIPInputStream gis = new GZIPInputStream(cis);
    byte []bit = new byte[100];
    while((gis.read(bit)) != -1)
    {
    fos.write(bit);
    fos.flush();

    }
    System.out.println("ok");

    gis.close();
    fos.close();
    Thread.sleep(10);
    client.close();
    }catch(Exception ex)
    {

    }
      

  2.   

    byte []bit = new byte[100]; 
    while(fis.read(bit) != -1)
    {
    gos.write(bit);//你认为一定可以把数组读满吗?
    }-----------------------byte []bit = new byte[100]; 
    int len
    while((len=fis.read(bit)) != -1)
    {
    gos.write(bit,0,len}
      

  3.   

    记着仔细看API说明,为什么他要返回一个读取到的字节数,因为你在读之前,你不知道流中到底可以读到多少字节
      

  4.   

    很高兴看到各位大哥写的程序。本小弟建了个群:9691599。希望热爱JAVA的朋友加进来一起探讨。希望高手们的指点。也希望初学者到来一起探讨。
      

  5.   

    to tanghuan():我也感觉是这个问题,但自己解决不掉,十分感谢!