送信側 - Android にあり、AsyncTask、doInBackground の一部です。基本的に、ファイル名、サイズ、画像データをサーバーサイドに送信します。
InetAddress serverIP = InetAddress.getByName(IP);
Socket client = new Socket(serverIP,SERVER_PORT);
System.out.println("Connected to Server\n");
System.out.println(imgFile.length());
//sending name of the file
PrintWriter name = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),true);
name.println(fileName);
name.flush();
//sending size of the file
name.println(imgFile.length());
name.flush();
//sending body
DataInputStream imgBodyIn = new DataInputStream(new FileInputStream(imgFile));
DataOutputStream imgBodyOut = new DataOutputStream(client.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
int len;
long filesize = imgFile.length();
while(filesize >=0&& (len=imgBodyIn.read(buffer,0,(int)Math.min(buffer.length,filesize)))>0){
imgBodyOut.write(buffer,0,len);
filesize-=len;
}
name.close();
imgBodyIn.close();
imgBodyOut.flush();
imgBodyOut.close();
client.close();
受信側
//receiving name
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String name = in.readLine();
System.out.println("Name of the File : " + name+".JPG");
//receiveing size info
String size = in.readLine();
System.out.println("Size of the File :"+size +"bytes");
//storing file
File f = new File("/home/ubuntu", name+".JPG");
FileOutputStream output = new FileOutputStream(f);
int len=0;
long received=0;
byte[] buf = new byte[BUFFER];
while(received<=Long.parseLong(size)&&(len=sock.getInputStream().read(buf))>0)
{
output.write(buf,0,len);
received +=len;
System.out.print("Receiving.."+received +"/"+size+"\r");
}
output.flush();
output.close();
in.close();
System.out.println("\n"+name+".JPG received");
System.out.println("Size received :"+f.length()+"bytes");
ファイルを送信しようとすると、正しいサイズ情報と名前が転送されます。しかし、完全なファイルを受け取ることができませんでした。一部のバイトが欠落しています。私が使用しているバッファサイズは 1024 です。
サンプルラン:
Waiting for client to connect..
Client Accepted
Name of the File : P1011474.JPG
Size of the File :714438bytes
Receiving..712997/714438
P1011474.JPG received
Size received :712997bytes
socket closed