client sends the file to server and server receives it and saves it. But when in the Client that Line(while ((len = outputFromServer.read(buf)) != -1)) comes the client stuckes i dont know why?
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.connect((new InetSocketAddress(host, port)),
SOCKET_TIMEOUT);
final File f = new File(
Environment.getExternalStorageDirectory()
+ "/wifip2pshared-"
+ System.currentTimeMillis() + ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
// send Data To Server
OutputStream stream = socket.getOutputStream();
FileInputStream file = new FileInputStream(
"/sdcard/samsung/Image/001" + ".jpg");
while ((len1 = file.read(buf1)) != -1) {
stream.write(buf1, 0, len1);
}
file.close();
// ////////////////////////////////
// ///////////////////////
// read Data from server
InputStream outputFromServer = socket.getInputStream();
FileOutputStream saveData = new FileOutputStream(
f);
while ((len = outputFromServer.read(buf)) != -1) {
saveData.write(buf, 0, len);
}
saveData.close();
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e("exception at client", e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
Log.e("exception at clientin socket close",
e.toString());
}
}
}
}
Server Side
try {
server = new ServerSocket(8988);
Socket client = server.accept();
final File f = new File(
Environment.getExternalStorageDirectory()
+ "/wifip2pshared-"
+ System.currentTimeMillis() + ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
// receive Data From Client
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
String a = "acb";
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
Log.e("In server reviving data", a);
}
fos.close();
// Send Data To Client
OutputStream stream = client.getOutputStream();
FileInputStream file = new FileInputStream(
"/sdcard/samsung/Image/001" + ".jpg");
while ((len1 = file.read(buf1)) != -1) {
stream.write(buf1, 0, len1);
}
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client sends the file to server and server receives it and saves it. But when in the Client that Line(while ((len = outputFromServer.read(buf)) != -1)) comes the client stuckes i dont know why?
read() on a socket stream will return -1 only if connection is closed or an error occurs. Server receives the data and saves it but never leaves the receiver loop to send data. Even if it would do the client wouldn't then leave its receiver loop either.
You must either close the connection or send file size before the actual file and receiving stops when given size was read.
Related
I'm trying to send multiple files from client to server using socket but when I click upload button it adds only one file second
Your copyFile() is not suitable for network transmissions.
You need to get rid of the two close() calls inside of copyFile(). On the client side, out.close() is closing the socket after the 1st file has been sent. On the server side, InputStream.close() is closing the socket after the 1st file has been received. It is the caller's responsibility to close the streams it passes to copyFile(), it is not copyFile()'s responsibility.
More importantly, for each file the client wants to send, copyFile() is not sending the file's byte count before sending the file's actual bytes, to indicate where each file ends and the next begins. So, on the server side, copyFile() does not know when to stop reading from the inputStream and will just keep reading endlessly until the connection is closed/broken.
As-is, copyFile() may work for copying files from one folder to another on the local system, but it is not suitable for copying files over a TCP network.
Try this instead:
Client side:
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(TAG, "Client socket - " + socket.isConnected());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(fileUri.size());
for(String file : fileUri)
{
//long length = file.length();
//dos.writeLong(length);
String name = file;
dos.writeUTF(name);
File f = new File(file);
sendFile(f, dos);
}
dos.close();
Log.d(TAG, "Client: Data written");
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
}
catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
void sendFile(File in, DataOutputStream out) throws IOException {
long fileLength = in.length();
out.writeLong(fileLength);
FileInputStream fis = new FileInputStream(in);
BufferedInputStream bis = new BufferedInputStream(fis);
byte buf[] = new byte[1024];
int len;
while (fileLength > 0) {
len = bis.read(buf);
if (len == -1) throw new IOException();
out.write(buf, 0, len);
fileLength -= len;
}
}
Server side:
try {
ServerSocket serverSocket = new ServerSocket(8988);
Socket client = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
Log.d(TAG, "doInBackground: " + filesCount);
//long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File(context.getExternalFilesDir("received"), Long.toString(System.currentTimeMillis()) + ".mp4" );
Log.d(TAG, "doInBackground: 1" );
File dirs = new File(context.getPackageName() + files[i].getParent());
Log.d(TAG, "doInBackground: 2" );
if (!dirs.exists()) dirs.mkdirs();
files[i].createNewFile();
Log.d(TAG, "server: copying files " + files[i].toString());
receiveFile(dis, files[i]);
}
serverSocket.close();
return "done";
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
return null;
}
void receiveFile(DataInputStream in, File out) throws IOException {
long fileLength = in.readLong();
FileOutputStream fos = new FileOutputStream(out);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
int len;
while (fileLength > 0) {
len = (fileLength >= 1024) ? 1024 : (int) fileLength;
len = in.read(buf, 0, len);
if (len == -1) throw new IOException();
bos.write(buf, 0, len);
fileLength -= len;
}
}
I want to transfer a file between server and client, Server is a Windows program written in Delphi with Indy and Client is an Android
this is my client code for reading from socket :
...
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[FileSize];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = IS.read(FBytes);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
} while (BytesRead > 0);
Log.d(TAG, "Download Loop Finished");
File will download but the problem is size of downloaded file is lower than original file and the socket read command stay on last read. in other words file has been downloaded but CurrProgress is lower than FBytes.length so while loop execute onetime more and program hangs on read command because there is no more data sent from server
I have been tested server with an windows program and there is no problem in the server code
I have tested many ways like this but no chance :
int BytesRead = IS.read(FBytes, 0, FBytes.length);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, CurrProgress, (FBytes.length - CurrProgress));
...
FileSize value is correct and came from server as a string value before reading file bytes
What goes wrong ?!, thanks ...
Edit :
Complete code do many other jobs but code of reading file is like this :
public void Run()
{
Running = true;
try{
try{
InetAddress ServerAddr = InetAddress.getByName(SERVER_IP);
S = new Socket(ServerAddr, SERVER_PORT);
Log.d(TAG, "Connecting ...");
Out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(S.getOutputStream())), true);
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
switch (Job) {
...
}
case GetFile: {
this.SendMessage(Cmd);
response = In.readLine();
if(response.equals("1"))
{
Hdlr.sendEmptyMessage(MSG_SERVER_ACCEPT);
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
}
else {
final Message Msg = new Message();
final Bundle B = new Bundle();
B.putInt("FSize", FileSize);
Msg.what = MSG_FILE_SIZE;
Msg.setData(B);
Hdlr.dispatchMessage(Msg);
try {
File TempDir, TempFile, MainDir, MainFile;
switch(FileType)
{
case 2 :
TempDir = new File(context.getCacheDir(), "TempMP3");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".mp3");
if(TempFile.exists()) {
TempFile.delete();
}
break;
default :
TempDir = new File(context.getCacheDir(), "TempLevel");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".zip");
if(TempFile.exists()) {
TempFile.delete();
}
}
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[4096];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
do {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
} while (CurrProgress < FileSize);
Log.d(TAG, "Download Loop Finished");
if (CurrProgress != FBytes.length) {
BOS.close();
Hdlr.sendEmptyMessage(MSG_ERROR_FILESIZE);
Log.d(TAG, "File Size Problem");
} else {
BOS.close();
Log.d(TAG, "File Downloaded successfully, Preparing to Unzip ... ");
try {
MainDir = new File(context.getFilesDir(), "Levels");
if(!MainDir.exists())
{
MainDir.mkdir();
}
File LevelDir = new File(MainDir, Integer.toString(FileIndex));
if(!LevelDir.exists())
{
LevelDir.mkdir();
}
else
{
LevelDir.delete();
}
FileInputStream fin = new FileInputStream(TempFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
MainFile = new File(LevelDir, ze.getName());
FileOutputStream FOut = new FileOutputStream(MainFile);
for (int c = zin.read(); c != -1; c = zin.read()) {
FOut.write(c);
}
zin.closeEntry();
FOut.close();
}
zin.close();
} catch (Exception e) {
Log.d(TAG, "Unzip Error : ", e);
}
}
} catch (Exception E) {
Err = 1;
Log.d(TAG, "Get File Error : ", E);
}
}
}
else
{
if (Listener != null)
{
Listener.callbackMessageReceiver(response);
Hdlr.sendEmptyMessage(MSG_ERROR_SERVER);
}
}
break;
}
...
}
}catch (Exception e)
{
Hdlr.sendEmptyMessage(MSG_ERROR_SEND);
Log.d(TAG, "Connect Error : ", e);
}
finally{
if(Out != null) {
Out.flush();
Out.close();
}
if(In != null)
{
In.close();
}
S.close();
Log.d(TAG, "Err Value is : " + Integer.toString(Err));
if(Err == 0)
{
Hdlr.sendEmptyMessage(MSG_SUCCESS);
}
Log.d(TAG, "Sending Ends");
}
}catch (Exception E){
Log.d(TAG, "Error : ", E);
}
}
CurrProgress is lower than FileSize ( the difference is about 4 or 5 KB ) and the while loop hangs on read command !
Problem solved, I will post it as answer, it may be useful
The problem was that server sends File immediately after sending FileSize and I think the BufferedReader gets some bytes of File so the size of bytes given by IS are lower than FileSize, example of Server :
...
WriteLn(FileSize);
Write(FileStream);
...
Now, Server first sends FileSize then wait for a response from client, after checking freespace in client it sends a Ready response to server and then Server sends the File Stream, for example :
...
WriteLn(FileSize);
Response := ReadLn();
if Response = "READY" then
Write(FileStream);
...
and codes in client are like this :
...
BufferedInputStream BIS = new BufferedInputStream(S.getInputStream());
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
...
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
this.SendMessage("NOT_READY");
}
else {
...
try {
this.SendMessage("READY");
byte[] FBytes = new byte[8192];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
while (CurrProgress < FileSize){
Log.d("DOWNLOAD", "Available : " + Integer.toString(BIS.availabl
BytesRead = BIS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
There is no problem and everything works fine
I want to let the user download a file from my android app with the web browser on his computer (in local network).
At first I wrote the code for this feature in eclipse on my computer and it worked fine. But when I try to run it in an android app (the file is copied from the assets path) I am not able to download the file anymore. Firefox just tells me that it couldnt download because the source file could not be read.
This ist my code in the app. It doesnt throw any errors.
public class test implements Runnable {
public boolean running = true;
ServerSocket servsock = null;
Context context;
String filename = "test.jar";
public test(Context con){
this.context=con;
}
public Integer createSocketandStart(){
for (int i=1234; i<2000; ++i){
try{
servsock = new ServerSocket(i);
servsock.setSoTimeout(1000000);
new Thread(this).start();
return i;
}catch(Exception e){
System.out.print("socket error");
}
}
return null;
}
public void run(){
File f= new File(context.getFilesDir(), filename);
try {
InputStream is = context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
while (running) {
try {
Socket connection = servsock.accept();
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
PrintStream pout = new PrintStream(out);
InputStream file = new FileInputStream(f);
pout.print("HTTP/1.0 200 OK\r\n" +
"Content-Type: application/octet-stream\r\n" +
"Content-Disposition: attachment; filename=\"" + filename + "\"\r\n" +
"Date: " + new Date() + "\r\n" +
"Server: FileServer 1.0\r\n\r\n");
byte[] buffer = new byte[1000];
while (file.available() > 0) {
out.write(buffer, 0, file.read(buffer));
}
out.flush();
if (connection != null) connection.close();
file.close();
pout.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
How to receive original content and file name from server side code.
Client Code
public void send1(Socket socket)
{
try
{
dataOutputStream = new DataOutputStream(socket.getOutputStream());
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "temp.txt");
FileInputStream fis = new FileInputStream(file);
//write file length
dataOutputStream.writeLong(file.length());
Log.i("File Size", "" + file.length());
//write file names
dataOutputStream.writeUTF(file.getName());
Log.i("File Name", "" + file.getName());
//write file to dos
byte[] buf = new byte[4092];
int n = 0;
while((n = fis.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
dataOutputStream.write(buf, 0, n);
}
dataOutputStream.flush();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as temp.txt and Content as Hello
Server Code
public void receive1(Socket socket)
{
try
{
inputStream = socket.getInputStream();
dataInputStream = new DataInputStream(inputStream);
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
int n = 0;
byte[] buf = new byte[4092];
//read file name
/*String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);*/
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file
while((n = dataInputStream.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
fos.write(buf, 0, n);
}
fos.flush();
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as test.txt and Content as temp.txtHello.
In this test.txt file, contains temp.txt. I am not getting file name from dataInputStream.readUTF().
Where I mistaken code...
If I called readUTF() method, then I am getting the Exception
Exception as
java.io.EOFException
at libcore.io.Streams.readFully(Streams.java:83)
at java.io.DataInputStream.readFully(DataInputStream.java:99)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:178)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:173)
at java.io.DataInputStream.readUTF(DataInputStream.java:169)
You wrote the Long before the String in the inputStream of the send method. What you did in the server code is that you are expecting to recieve String before the Long which in reserved on what you did in your send method.
solution:
switch reading long first then string
sample:
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file name
String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);
Here's the code to download a 3pg video file. Maybe one can give me an idea about what's wrong with it. I really need help. Can't get it to download the file:
Blockquote
protected String doInBackground(String... sUrl) {
byte[] data = new byte[1024];
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("URL"," " + connection.getURL());
Log.v("File ", "length = " + connection.getContentLength());
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos);
while ((count = input.read(data)) != -1) {
Log.v("Count="," " + count);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.v("Download","Finished");
} catch (IndexOutOfBoundsException iobe) {
iobe.getStackTrace();
} catch (IOException ioe) {
ioe.getStackTrace();
} catch (NullPointerException npe) {
npe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
And strangely enough, sometimes the method connection.getContentLength() returns -1 instead of the file length.