【问题标题】:How to receive socket correctly如何正确接收套接字
【发布时间】:2013-08-27 07:20:29
【问题描述】:

我正在尝试在两个 android 设备之间发送图片,但我无法弄清楚传输问题。有人告诉我修改 wile 循环,但它仍然不起作用。 当我在设备上测试我的项目时,连接没有问题。但是,随着传输任务的开始,发送客户端停止,接收端出现“传输错误”消息。 有谁知道我可以对我的程序做些什么?这是我发送和接收的两个主要部分。

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

发送部分:

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()));”并捕获异常。

再次感谢。

【问题讨论】:

  • 请提供捕获异常的堆栈跟踪。
  • 08-26 22:49:25.950: D/OpenGLRenderer(18754): 启用调试模式 0 08-26 22:54:00.510: D/libEGL(19098): 加载 /system/lib/ egl/libEGL_tegra.so 08-26 22:54:00.530: D/libEGL(19098): 加载 /system/lib/egl/libGLESv1_CM_tegra.so 08-26 22:54:00.540: D/libEGL(19098): 加载 / system/lib/egl/libGLESv2_tegra.so 08-26 22:54:00.570: D/OpenGLRenderer(19098): 启用调试模式 0 这里是 logcat,谢谢
  • 好吧,你没有记录异常。所以它不在logcat中..
  • 我试过了,但还是不行。我发布了 catlog stackoverflow.com/questions/18470975/… 如果您有任何想法,请告诉我。非常感谢。

标签: android sockets


【解决方案1】:

您正在使用 writeUTF() 写入文件长度,但您从未读取它。如果您要在发送图像后关闭套接字,则不需要长度:只需发送然后关闭套接字。如果您确实需要长度,请使用 readUTF()读取它,然后从套接字准确读取那么多字节到目标。

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

编辑

大约百万次(希望我每次都有 $),在 Java 中复制流的规范方法是:

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

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

【讨论】:

  • 所以如果我只想发送一张图片然后关闭套接字。我需要while循环吗?或者只是丢弃循环而不是 os.write(buffer, 0, bis.read(buffer))?
猜你喜欢
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 2014-08-27
  • 2016-09-14
相关资源
最近更新 更多