服务器端发送几张图片,客户端接收并保存在SD卡中.有时客户端能接收成功,有时有不成功.求解!!!!!看代码:
服务器端:
//图片结束标志位
byte[] end_b = new byte[1024];
for(int bi=0;bi<1024;bi++)
   end_b[bi] = 0;
end_b[0]=7;
end_b[1]=8;
end_b[2]=9;
end_b[3]=1;
end_b[4]=2;
end_b[5]=3;
for(int num=0;num<4;num++)
{
   FileInputStream file_in_stream = new FileInputStream(new File(".\\Images\\"+num+".JPG");   
   byte[] b = new byte[1024];
   while(file_in_stream.read(b,0,1024)>0)
   {
        out_stream_send.write(b,0,1024);
        out_stream_send.flush();
    }
    //发送结束标志位,客户端接收到结束标志位后便可以进行下一张图片的接收
    out_stream_send.write(end_b,0,1024);
    out_stream_send.flush();
}
System.out.println("发送图片完毕,关闭socket");
CliSocket.shutdownOutput();
CliSocket.close();
android客户端代码:
//获取手机SD卡的目录,自己创建一个文件夹
File sd = Environment.getExternalStorageDirectory();//得到/SDCARD/
String path = sd.getPath() + "/erewen";
File file_dir = new File(path);
if(!file_dir.exists())
{
    //不存在目录就创建一个目录
    file_dir.mkdir();
}
for(int i=0;i<4;i++)
{
    FileOutputStream file_out_stream = new FileOutputStream(new File(path+"/"+i+".JPG"));
    byte[] b_image = new byte[1024];
    while(in_stream2.read(b_image,0,1024)>0)
    {
        file_out_stream.write(b_image,0,1024);
        //当接收到结束标志信息后便跳出while循环,准备下一张图片存储
        if(b_image[0]==7&&b_image[1]==8&&b_image[2]==9&&b_image[3]==1&&b_image[4]==2&&b_image[5]==3)
              break;
    }
    //清空缓存,关闭连接,准备第二张图片
    file_out_stream.flush();
    file_out_stream.close();
}
CliSocket2.close();
每张图片大概50多K.也试过成功传104K的,所以应该不跟图片大小有关.android是真机通过WIFI和服务器同个局域网..我也试过服务器和客户端都是在电脑上传图片.相同的思路代码电脑接收没出过问题.就是在android手机上客户端接收时有时接收一两张不成功,有时成功.请求高人解答下.小弟在此先谢谢各位.

解决方案 »

  1.   

    服务器端和客户端是通过TCP socket连接的
      

  2.   

    丢包了?先不要传图片,ping 100次看看结果……
      

  3.   

    问题好像找到了,服务器端在发送图片之前还发送了一次文本内容给客户端.我讲发送文本内容的这段代码注释掉后就能接收到图片.但就图片有时会失真,可能是我的发送和接收都是用1024个字节来发和接,将图片添加了一些多余的字节.但如何在发送文本内容后还能成功发图片字节呢?发送文本内容代码:
    OutputStream out_stream_send = CliSocket.getOutputStream();
    OutputStreamWriter out_writer_send = new OutputStreamWriter(CliSocket.getOutputStream(),"GB2312");
    BufferedWriter buf_writer_send = new BufferedWriter(out_writer_send);
    String content = null;
    //从数据库中拿文本内容保存在content对象中.
    while(rs_send1.next())
    {
       if(title.equals(rs_send1.getString("子子标题")))
       {
        content=rs_send1.getString("正文");
       System.out.println("发送内容为:"+content);
       }
    }
    buf_writer_send.write(content+"\r\n\r\n");
    buf_writer_send.flush();
    System.out.println("发送完文本了!接下来要发图片了!");*/
      

  4.   

    算了.这分数给我另一个账号吧.
    我将传文本内容和传图片分开来两部分.传图片这一部分服务器端首先获取图片的大小,将其保存在一个4个byte的数组中传给客户端,客户端接收到后将其转成一个int类型,然后接收服务器端发送过来的图片信息.
    之前的接收图片代码写得不好,因为客户端每次从SOCKET接收到的字节数不一定是1024.
    while(in_stream2.read(b_image,0,1024)>0)
    {
     file_out_stream.write(b_image,0,1024);
      //当接收到结束标志信息后便跳出while循环,准备下一张图片存储 
    if(b_image[0]==7&&b_image[1]==8&&b_image[2]==9&&b_image[3]==1&&b_image[4]==2&&b_image[5]==3)
      break;
    }
    所以要加一个int length=in_stream2.read(b_image,0,1024);来判断客户端接收了多少字节数