Android sending file name via socket communication [duplicate] - java

This question already has answers here:
How do I send file name with file using sockets in Java? [duplicate]
(3 answers)
Closed 6 years ago.
I am able to send Files through socket and receive on other ends . Now i want to send even file name so that after receiving file and saving file from socket i can save the name of file. What to add in client to send filename and in server to receive filename thanks in advance to all
Client.java
try {
clientSocket = new Socket(targetIP, port);
os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
signalActivity("About to start handshake");
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(fileToSend);
BufferedInputStream bis = new BufferedInputStream(fis);
// long BytesToSend = fileToSend.length();
while(true)
{
int bytesRead = bis.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
//BytesToSend = BytesToSend - bytesRead;
os.write(buffer,0, bytesRead);
os.flush();
}
fis.close();
bis.close();
br.close();
isr.close();
is.close();
pw.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
catch(Exception e)
{
}
Server.java
try {
welcomeSocket = new ServerSocket(port);
while(true && serviceEnabled)
{
socket = welcomeSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String inputData = "";
// String savedAs = "WDFL_File_" + System.currentTimeMillis();
//save the original name and extention
File file = new File(saveLocation, savedAs);
byte[] buffer = new byte[4096];
int bytesRead;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while(true)
{
bytesRead = is.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
bos.write(buffer, 0, bytesRead);
bos.flush();
}
bos.close();
socket.close();
//Start writing to file
}
} catch (IOException e) {
}
catch(Exception e)
{
}

Your client should send the file name first. After that the contents of the file.
The server should read the file name first so the following content of the file can be saved under the same file name.

Related

Receiving file on connection timed out

I made a server that sends a text file to the client (Android) and I'm only getting the file when I'm getting connection timed out.
Why the "connection timed out" is happening in the first place? and also, it takes like 1 minute to the file to be received (1MB).
Server:
FileInputStream fis = new FileInputStream(
new File("123.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
byte[] mybytearray = new byte[8192];
OutputStream os;
try {
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Client:
InputStream in;
int Size = 0;
try {
Size = clientSocket.getReceiveBufferSize();
in = clientSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
byte[] buffer = new byte[Size];
int read;
while ((read = dis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Any idea how to fix this problem?
You don't close stream on the server side. So nobody knows that this is the end of stream and wait continues till time out. Add close() like this:
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
os.close();
Also, on client side you should expect zero input. Its is OK for slow connection. Only -1 means that connection is closed. Change code like this:
while ((read = dis.read(buffer)) > -1)

Socket Server Downloading Folders containings, but not a specific file

im having a trouble here, here i built this Socket server to download files, it downloades the files inside of a folder, but it doesnt download a specified file name an returns null, could you guys help me where should i change in this server to do so?
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
String Request = (String) sInput.readObject();
System.out.println("request is:"+Request);
String[] todoname=Request.split("\\#reza-hp");
String name=todoname[0];
System.out.println("Connecting...");
File filcheck = new File("D://Users//ProfileImages//"+name+"
//"+"ProfileImage,imagechange_1,"+name+",.jpg");
System.out.println(filcheck);
if (filcheck.exists()){
fil = new File("D://Users//ProfileImages//"+name+"
//"+"ProfileImage,imagechange_1,"+name+",.jpg");
}else{
fil = new File("D://Users//Default//");
}
System.out.println(fil);
File[] Files=fil.listFiles();
System.out.println(Files);
for (int count=0;count < Files.length;count ++){
System.out.println(Files[count].getName());
}
os = socket.getOutputStream();
dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count=0;count<Files.length;count ++){
dos.writeUTF(Files[count].getName());
}
for (int count=0;count<Files.length;count ++){
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count=0;count<Files.length;count ++){
int filesize = (int) Files[count].length();
byte [] buffer = new byte [filesize];
FileInputStream fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
fis.close();
dos.flush();
//close socket connection
// socket.close();
}
// Toast.makeText(getApplicationContext(),"Transfer file is
completed!!", Toast.LENGTH_LONG).show();
dos.close();
os.close();
//socket.close();
thanks
Well fixed it , here i post the singe file downloader, and in the question is the File's containing's download from any type,image,music,video , both are very viable for who ever needs to use, good luck.
String Type;
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output
Streams");
while (!jobdone){
try
{
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
String Request = (String) sInput.readObject();
System.out.println("request is:"+Request);
String[] todoname=Request.split("\\#reza-hp");
String name=todoname[0];
System.out.println("Connecting...");
File filcheck = new File("D://Users//ProfileImages//"+name+"
//"+"ProfileImage,imagechange_1,"+name+",.jpg");
System.out.println(filcheck);
if (filcheck.exists()){
fil = new File("D://Users//ProfileImages//"+name+"
//"+"ProfileImage,imagechange_1,"+name+",.jpg");
}else{
fil = new File("D://Users//Default//");
}
System.out.println(fil);
// File[] Files=fil.listFiles();
// for (int count=0;count < Files.length;count ++){
System.out.println(fil.getName());
// }
os = socket.getOutputStream();
dos = new DataOutputStream(os);
dos.writeInt(1);
// for (int count=0;count<Files.length;count ++){
dos.writeUTF(fil.getName());
// }
// for (int count=0;count<Files.length;count ++){
int filesize = (int) fil.length();
dos.writeInt(filesize);
// }
// for (int count=0;count<Files.length;count ++){
byte [] buffer = new byte [filesize];
FileInputStream fis = new FileInputStream(fil.toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
fis.close();
dos.flush();
//close socket connection
// socket.close();
// Toast.makeText(getApplicationContext(),"Transfer file is
completed!!", Toast.LENGTH_LONG).show();
dos.close();
os.close();
//socket.close();
}

sending file to server and receiving it back on client side tcp java

1.client is sending file succesfully to server
2.server receives file successfully
But
3. when server tries to send this file back to client ,after working on received file( sent by client) following error occurs :
socket:null
connection is closed
This is sending file method back to client
"server code: "
public void sendFileBack(String fileName)
throws UnknownHostException,FileNotFoundException, IOException {
Socket sock = new Socket("192.168.0.103", 13267);
String tmpName=fName.replace(".mcrl2", ".lps");
File myFile = new File("out" + "\\" +tmpName );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
//Sending file data to the server
os.write(mybytearray, 0, mybytearray.length);
os.flush();
console.append("\n\n Output file transfered successfully \n \n");
//Closing socket
sock.close();
}
This is receiving file method back from server
"client code:"
private void receiveFileBack() throws IOException {
int bytesRead;
int port;
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.print("accepted connection"+clientSocket);
InputStream in = clientSocket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.print(fileName+"..........");
File f =new File("serverOut\\"+fileName);
OutputStream output = new FileOutputStream("serverOut\\"+fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 &&
(bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
serverStatus.append("Reading file..\n");
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
// Closing the FileOutputStream handle
output.close();
output.flush();
}
}

Showing corrupted but working in java but not in android

I have a server client file transfer program which works fine in java .but i copied it and changed the file location d:/ to environm.....
The problem is the filesize is lesser than sending one, hence its shown as corrupted.. Any idea .
SERVER SIDE
public class Server
{
// create socket
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
while(true)
{
ServerSocket servsock = new ServerSocket(13000);
System.out.println("Main Waiting...");
Socket socket = servsock.accept();
System.out.println("Accepted connection : " + socket);
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
long filesize = new Long(in.readLong());
System.out.println("received Size:"+filesize);
// read file name
String fname=in.readUTF();
System.out.println("server : file name: "+fname);
String prefix=fname.substring(0,fname.lastIndexOf('.')).trim();
String suffix=fname.substring(fname.lastIndexOf('.'),fname.length()).trim();
String file = prefix + suffix;
System.out.println("received name:"+file);
File f=new File("F:/Users/achu/Desktop/"+ file);// changed this in android
f.createNewFile();
// receive file
byte [] mybytearray = new byte [(int)(filesize)];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
System.out.println("current"+current);
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(current<filesize && bytesRead >-1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
is.close();
socket.close();
servsock.close();
}
}
CLIENT SIDE
public class Client
{
Socket socket=new Socket("101.59.43.58",13000);
System.out.println("Connectedddd");
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
File file = new File("d:/my.pdf");
out.writeLong(file.length());
out.flush();
out.writeUTF(file.getName());
byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Send:"+mybytearray.length);
OutputStream ous = socket.getOutputStream();
System.out.println("Sending...");
ous.write(mybytearray,0,mybytearray.length);
ous.flush();
bis.close();
ous.close();
System.out.println("closing socket...");
socket.close();
}

Able to send images over socket but not text files

My client can send Images normally to server, but when it comes to text files they arrive empty. Any ideas what am I doing wrong? I'd really appreciate help, because I have been trying to make this work for many days now. Thanks.
Here is the server code:
class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
and here is the client code:
public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.newLine();
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
You are prematurely closing BufferedReader on server side before reading all the data. This essentially closes the connection.
You should not use Reader or Writer for non-character streams like binary image data. And you should not mix BufferedReader with any other stream wrapper for the same stream since it may read as many data as it fills in buffer.

Categories