我通过在android中使用套接字编程来传输文件 文件传输成功,但是当我在客户端打开该文件时,它不包含任何数据,因为它包含0字节数据
我的客户端代码在这里:
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Abstract.docx");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >=0)
{
current += bytesRead;
}
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
long start = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
socket.close();
和我的服务器端代码在这里
while (true) {
Socket socket = serverSocket.accept();
////////////////////////////////
File myfile=new File("/storage/sdcard0/Abstract.docx");
byte[] mybytearray=new byte[(int)myfile.length()];
FileInputStream fis =new FileInputStream(myfile);
BufferedInputStream bis=new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=socket.getOutputStream();
System.out.println("Sending.........");
msg.setText("Sending 123.exe..........");
os.write(mybytearray,0,mybytearray.length);
os.flush();
socket.close();
//////////////////////////////////////////////////////
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
我在手机上运行它,而不是在模拟器上运行