两台android设备发送图片。
发送端:
Socket socket = null; try { socket = new Socket(ip, 8888); byte[] bytes = ScreenCapUtil.ScreenCapToByte(); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeInt(bytes.length);//发送的时候忘记添加了文件的大小。
out.write(bytes); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); }
接受端:
try { ServerSocket server = new ServerSocket(8888); Socket socket = server.accept(); DataInputStream dos = new DataInputStream(socket.getInputStream()); int size = dos.readInt();//因为发送时忘记添加文件大小。所以size的为负数
System.out.println("len = " + size); byte[] data = new byte[size];//下标为负数所以出错了。
int len = 0; while (len < size) { len += dos.read(data, len, size - len); }
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
handler.sendEmptyMessage(0);
// System.out.println("data = " + data);
dos.close(); socket.close(); server.close();
} catch (IOException e)
{ e.printStackTrace(); }