2013-08-25 67 views
0

我试图发送两个android设备之间的图片,但有一个传输问题,我想不出。有人告诉我修改这个可疑的循环,但它仍然不起作用。 当我在设备上测试我的项目时,连接没有问题。但是,随着传输任务的开始,发送方客户端被停止,接收方显示“传输错误”消息。 有没有人知道我可以对我的程序做些什么?这里是我发送和接收的两个主要部分。如何正确接收插座

我会非常感谢任何帮助。谢谢。

发送部分:

s = new Socket("192.168.0.187", 1234); 
Log.d("Tag====================","socket ip="+s); 

File file = new File("/sdcard/DCIM/Pic/img1.jpg"); 
FileInputStream fis = new FileInputStream(file); 
din = new DataInputStream(new BufferedInputStream(fis)); 
dout = new DataOutputStream(s.getOutputStream()); 
dout.writeUTF(String.valueOf(file.length())); 
byte[] buffer = new byte[1024]; 
int len = 0; 
while ((len = din.read(buffer)) != -1) { 
    dout.write(buffer, 0, len); 
    tw4.setText("8 in while dout.write(buffer, 0, len);"); 
    } 
dout.flush(); 

发送部分可以顺利工作,没有埃罗出现了while循环痊愈了

后接收部分:

try { 
File file = new File("/sdcard/DCIM/img1.jpg"); 
DataInputStream din = new DataInputStream(new BufferedInputStream(client.getInputStream())); 
bis = new BufferedInputStream(client.getInputStream()); 
Log.d("Tag====================","din="+s); 
    FileOutputStream fos = new FileOutputStream(file); 
    dout = new DataOutputStream(new BufferedOutputStream(fos)); 
    byte[] buffer = new byte[1024]; 
    int len = 0; 
    while ((len = bis.read(buffer)) != -1) { 
      dout.write(buffer, 0, len); 
      } 


    dout.flush(); 
    dout.close(); 
    } catch (Exception e) { 
    handler.post(new Runnable() { 
    public void run() { 
    tw1.setText("transmission error"); 
    }}); 

容纳部分周围似乎连卡在“DataInputStream din = new DataInputStream(new BufferedInputStream(client.getInputStream()));”并抓住例外。

再次感谢。

+0

请提供catched异常的堆栈跟踪。 – flx

+0

08-26 22:49:25.950:D/OpenGLRenderer(18754):启用调试模式0 08-26 22:54:00.510:D/libEGL(19098):loaded /system/lib/egl/libEGL_tegra.so 08/26 22:54:00.530:D/libEGL(19098):loaded /system/lib/egl/libGLESv1_CM_tegra.so 08-26 22:54:00.540:D/libEGL(19098):loaded/system/lib/egl/libGLESv2_tegra.so 08-26 22:54:00.570:D/OpenGLRenderer(19098):启用调试模式0 这里是logcat,谢谢 –

+0

嗯,你没有记录异常。所以它不是在logcat .. – flx

回答

0

你正在用writeUTF()编写文件长度,但是你永远不会读它。如果您要在发送图像后关闭套接字,则不需要长度:只需发送然后关闭套接字即可。如果你确实需要这个长度的话,读取吧,用readUTF(),然后从套接字读取到这个字节的许多字节。

如果你需要这个长度,用writeInt()或writeLong()发送它比将数字转换为一个字符串更有意义,将它转换为writeUTF()格式,然后将其转换为字符串另一端用readUTF(),然后将其转换回int或long。当然,这也意味着适当地使用readInt()或readLong()。

编辑

有关百万次(希望我每次一$),复制Java中的流规范的做法是:

while ((count = in.read(buffer)) > 0) 
{ 
    out.write(buffer, 0, count); 
} 

其中“数”是int和'buffer'是长度大于0的字节数组,最好是8192或更多。请注意,你必须循环;您必须将read()结果存储在变量中;你必须测试这个变量;你必须在write()调用中使用它。

+0

所以,如果我只想发送一张图片然后关闭套接字。我需要while循环吗?或者放弃循环而不是os.write(buffer,0,bis.read(buffer))? –

+0

@DoReMi请参阅编辑。 – EJP