I am trying to send Files with JAVA. My problem is that the client never knows if the end of the file is reached or not. So the while loop of the Client never ends. Please help me.
Server (sends Data to Client)
File myFile = new File("C://LEGORacers.exe");
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = null;
OutputStream os = null;
bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
Client (gets Data from Server)
byte[] buf = new byte[1024];
InputStream is = null;
int bytesRead = 0;
is = client.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream("C://copy.exe");
BufferedOutputStream bos = new BufferedOutputStream(fos);
try {
while (-1 != (bytesRead = is.read(buf, 0, buf.length))) {
// This while loop never ends because is.read never returns -1 and I don't know why...
bos.write(buf, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
is.close();
bos.flush();
bos.close();
fos.close();
}
Did you close your OutputStream on your Server? If not, your loop might be perpetually setting bytesRead to 0, so you may need to close that stream.
If you need the Server's OutputStream to still be open after sending data, you could also send the size of the data in bytes at the beginning of the stream, and loop until you have all of the bytes the Server indicates it will send.
Close the socket output stream on the server. Flushing doesn't terminate the stream, which is what you need to do to send the signal that the server is done writing. From what you posted, I don't see where you close the output stream on the server side.
Related
I'm in the midst of trying to send a file, and in particular large files, from server to client. I can send small files but atm large files do not work.
Server
Socket socket = serverSocket.accept();
byte[] data = new byte[(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(data, 0, data.length);
OutputStream oStream = socket.getOutputStream();
oStream.write(data, 0, data.length);
Client
byte[] data = new byte[4096];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("output.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(data, 0, data.length);
int counter = bytesRead;
// while (-1 != (bytesRead = is.read(data, 0, data.length)))
// {
// bos.write(data, 0, bytesRead);
// }
bos.write(data, 0, bytesRead);
With this code i'm able to transfer a simple text file successfully. With the commented out section uncommented (and excluding the last line) i thought i'd still be able to send a simple text file and in addition large files like a 200mb video. Obviously, it failed and here i am. Hope someone could give me a hand.
EDIT: Error with while loop (and no last line) is that nothing is written in the txt file
Get rid of the first read and the last write and just use the code that is commented out. That's the only code that actually works.
I have my client server chat
Client sends files and server receives them. But, the problem is that, i don't think that files are received properly because when i check the size of the files i see the difference is halfed for some reasons!
I am using GUI to browse for files in the client side, and then i'm sending a command to the server to know that the client is sending a file. But it is not working
Here is the client and server
public void sendFiles(String file) {
try {
BufferedOutputStream outToClient = null;
outToClient = new BufferedOutputStream(sock.getOutputStream());
System.out.println("Sending file...");
if (outToClient != null) {
File myFile = new File( file );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
this.out.println("SF");
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
this.out.flush();
outToClient.flush();
outToClient.close();
System.out.println("File sent!");
return;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Server
public void recvFile() {
try {
byte[] aByte = new byte[1];
int bytesRead;
InputStream is = null;
is = sock.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/Users/Documents/Received.png");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
// clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone help me with this issue? As i don't know how to properly send and receive files
Thank you
You are using two copy techniques, and they are both wrong.
First:
byte[] mybytearray = new byte[(int) myFile.length()];
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
Here you are assuming:
That the file fits into memory.
That the file length fits into an int.
That read() fills the buffer.
None of these assumptions is valid.
Second:
byte[] aByte = new byte[1];
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
Here you are:
Using a ridiculously small buffer of one byte.
Writing an extra byte if the file length is zero.
Using a do/while where the situation naturally calls for a while (as 99.99% of situations do), and therefore:
Using two read() calls, and only correctly checking the result of one of them.
Pointlessly using a ByteArrayOutputStream, which, as above, assumes the file fits into memory and that its size fits into an int. It also pointlessly adds latency.
Throw them both away and use this, at both ends:
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
where:
in is a FileInputStream in the case of sending the file, or the socket input stream in the case of receiving the file.
out is a FileOutputStream in the case of receiving the file, or the socket output stream in the case of sending the file
I just realized that DataInputStream and DataOutputStream in writing reading socket
could be used to differentiate the input that was coming over.
Check this code:
Server Side. (receiving string or file)
Socket bSock = serverSocket.accept();
DataInputStream inp = new DataInputStream(bSock.getInputStream());
int iCode = inp.readInt();
switch (iCode) {
case Request.STATE_FILESHARING:
byte bp[] = new byte[iCode];
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = inp.read(bp, 0, bp.length);
bos.write(bp, 0, bytesRead);
bos.close();
break;
case Request.STATE_CONVERSATION:
requestFound = new Request(inp.readUTF());
sendToUI(requestFound);
break;
}
Client Side. (sending string or file)
Socket socket = new Socket(myServerAddress, SocketServerPORT);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
if (isThisFileMode()) {
File myFile = new File(sLocationFile);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
out.writeInt(Request.STATE_FILESHARING);
out.write(mybytearray, 0, mybytearray.length);
out.flush();
} else {
out.writeInt(Request.STATE_CONVERSATION);
out.write(obReq.toString().getBytes());
out.flush();
}
But I ended up with Error. System crashed!
Anything that I forgot to add?
You're using readUTF() but not writeUTF(). Nearly all the methods of DataInputStream and DataOutputStream are symmetrical: if you call readXXX() you must call writeXXX() at the other end.
You're making the usual mistake of assuming that read() fills the buffer. It is only contracted to transfer at least one byte. You must loop:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
You need to close the socket at both server and client.
I run the server and client on separate cmd windows. The server prints out "Upload successful" and indeed the file gets uploaded to the server but the client freezes and i have to quit the client process using Ctrl+C. It seems to me that the client cannot break out of the while loop. Please tell me where i am going wrong?
(The code snippets are parts of much larger code body that i am writing to implement file read, write, read/write-lock, delete file etc from the server. Once a request to upload the file from the client is handled by the server I want the process to return to the command line menu i have incorporated with the client program[not shown below]. So it is important that the client returns to that user interface. Any help is greatly appreciated. Thanks in advance! )
Client side:
// initialized client and server connection made...
BufferedReader filePath = new BufferedReader(new InputStreamReader(System.in));
String pathname = filePath.readLine();
try{
File file_to_upload = new File(pathname);
byte[] bytearray = new byte[(int) file_to_upload.length()];
OutputStream os = client1.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file_to_upload));
do {
bis.read(bytearray, 0, bytearray.length);
os.write(bytearray, 0, bytearray.length);
os.flush();
bis.close();
} while (bis.read(bytearray, 0, bytearray.length)!= -1);
}
catch(FileNotFoundException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}
System.out.println("\n" + inFromServer.readLine() + "\n");
client1.close();
break;
server side:
byte[] mybytearray = new byte[1];
InputStream is = server1accept.getInputStream();
FileOutputStream fos = new FileOutputStream("234rews");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
outToClient.writeBytes("Uploaded");
System.out.println("Upload Successful");
Both your copy loops are incorrect. The canonical way to copy between streams in Java is:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
At present you are doing extra reads and ignoring read() results and all kinds of other strange things. Use this code at both ends, with any buffer size greater than zero.
I have a Java server class like this:
ServerSocket servsock = new ServerSocket(63456);
boolean read = false;
while (!read) {
Socket sock = servsock.accept();
int length = 1024;
byte[] mybytearray = new byte[length];
OutputStream os = sock.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
while (true) {
int i = bis.read(mybytearray, 0, mybytearray.length);
if (i == 1) {
break;
}
os.write(mybytearray, 0, mybytearray.length);
os.flush();
}
sock.close();
read = true;
}
`
And the client is like this:
Socket sock = new Socket("127.0.0.1", 63456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:/tmp/NEWtmp.rar");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
while(bytesRead != -1 ) {
bos.write(mybytearray, 0, bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
}
bos.close();
sock.close();
One question is: Why the loop does not stop at the end of the file?
A second question would be, why is also so slow?
It does not stop because
if (i == 1) {
in your server source should be
if (i == -1) {
Or, if you want to be really safe:
if (i <= 0) {
Also, you risk data corruption with this line:
os.write(mybytearray, 0, mybytearray.length);
You should change this to:
os.write(mybytearray, 0, i);
On performance -- move the os.flush(); call to outside the while loop. When you flush a network stream, you are forcing it to dispatch any buffered data to the network. This is forcing the network layer to send and acknowledge 1024-byte TCP payloads (larger Ethernet payloads, of course) which is probably significantly smaller than your PMTU. You only need to flush when you are done sending data, or when you want the client to receive the buffered data now. Removing the flush call from each iteration will allow the OS-level network buffer to do its job, and segment the data into as few packets as possible.
Second question - your client reads bytes directly from the raw socket stream. Use the BufferedInputStream/BufferedOutputStream decorators, this should increase performance:
Server Side
BufferedOutputStream os = new BufferedOutputStream(sock.getOutputStream());
Client side
BufferedInputStream is = new BufferedInputStream(sock.getInputStream());
The raw streams are not buffered (AFAIK) so you have to add the buffering manually, if needed.