I'm trying to receive a Picture on my Android phone from Server using socket programming.I use this code but in.read() in 4th line always returns -1.
How can I fix this problem?
Client Code:
try {
x = new byte[picLength2];
int current = 0;
int byteRead = in.read(x, 0, x.length);
current = byteRead;
do {
byteRead = in.read(x, current, (x.length - current));
if (byteRead >0) {
current += byteRead;
}
} while (byteRead > -1);
}catch (IOException e){
e.printStackTrace();
}
Server Code:
try {
File myFile = new File("C:/onlinegame/null.jpg");
mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(mybytearray);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
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'm developing an Android application sending files from one device to another.
Establishing the connection between both devices works perfectly, but there is something going wrong while transferring the file.
On the receiving device, the file gets created but unfortunately it's empty.
This is my code for handling the incoming file:
try {
byte[] buffer = new byte[1024];
int bytes = 0;
boolean eof = false;
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "test.jpg");
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (!eof) {
bytes = mmInStream.read(buffer);
int offset = bytes - 11;
byte[] eofByte = new byte[11];
eofByte = Arrays.copyOfRange(buffer, offset, bytes);
String message = new String(eofByte, 0, 11);
if(message.equals("end of file")) {
os.flush();
os.close();
eof = true;
} else {
os.write (buffer);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Using the DataInputStream/DataOuputStream solved the problem.
I'm trying to write and then read file:
private void writeToFile(String data,String filename) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
serviceNotifer("FILE WRITE", "ERROR", 687);
}
}
writeToFile("SOMETEXT!", "input.bin");
/* try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
File file = new File("input.bin");
FileInputStream fis = null;
try {
serviceNotifer("WriteFile", "Stop2", 922);
fis = new FileInputStream(file);
int bytesRead=0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
UpdateFileString=fis.toString();
serviceNotifer("FILE C:", UpdateFileString, 922);
int ByteNum=UpdateFileString.length();
SentNewIndexVal(0xE001,ByteNum);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.toString());
serviceNotifer("FILE", "ERROR1"+ e.toString(), 687);
} catch (IOException e) {
System.out.println("Exception reading file: " + e.toString());
serviceNotifer("FILE", "ERROR2", 687);
} finally {
try {
if (fis != null) fis.close();
} catch (IOException ignored) {
}
}
After recording, the application becomes larger than 15 kilobytes. But I get oshmbku "ERROR1" - File not found. Where is my mistake? I think it's related with file path...
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();
}
}
}
}
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.