How to receive socket correctly
I'm trying to send the pictures between two android devices, but there is
a transmission problem I can't figure out. Someone tell me to revise the
wile loop, but it still do not work. When I tested my project on the
device, there wasn't problem with the connection. But, as the transmission
task started, the sending client was stopped and "transfer erro" msg
showed up on the receiver. Is there anyone knows what can I do to my
program? Here are my two mainly parts of sending and receiving.
I'll be very appreciative of any help. Thank you.
sending part:
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();
the sending part can work smoothly and no erro showed up after the while
loop overed
receiving part:
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");
}});
About the receiving part seems even stuck at the "DataInputStream din =
new DataInputStream(new BufferedInputStream(client.getInputStream()));"
and catch the exception.
Thanks again.
No comments:
Post a Comment