java socket programming to send and receive file between two machines - java

I am trying to communicate between two machines using socket programming.
What I basically need is both machines should be able to send and receive files. The code I am pasting below is not showing any error but the server side program seems to be running indefinitely, i.e., it is not terminating. It got stuck on the line marked with comment stuck here.
In this code, initially, server is sending the file named "file.txt" and client is receiving it and saving the file with name "copy.txt". Later client is sending a file named "file2.txt" and server is receiving and saving it with name "copy2.txt".
Can someone please tell me the error and suggest some improvements?
//server side code
import java.net.*;
import java.io.*;
public class server
{
public static void main (String [] args ) throws IOException
{
//sending file started
ServerSocket serverSocket = new ServerSocket(16167);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("/Users/abhishek/desktop/file.txt");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
System.out.println("File transfer complete");
//socket.close();
//sending comleted
//receiving file started
int filesize=1022386;
int bytesRead=0;
int currentTot = 0;
byte [] bytearray1 = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy2.txt");
//fos.flush();
BufferedOutputStream bos = new BufferedOutputStream(fos);
//bos.flush();
System.out.println("not moving ahead!!!");//program stucked here
bytesRead = is.read(bytearray1,0,bytearray1.length);
currentTot = bytesRead;
System.out.println("current"+currentTot);
do
{
bytesRead = is.read(bytearray1, currentTot, (bytearray1.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
System.out.println("current"+currentTot);
} while(bytesRead > -1);
System.out.println("outside current"+currentTot);
bos.write(bytearray1, 0 , currentTot);
bos.flush();
//receiving complete
System.out.println("Receving file completed");
socket.close();
}
}
//client side code
import java.net.*;
import java.io.*;
public class client
{
public static void main (String [] args ) throws IOException
{
int filesize=1022386;
int bytesRead=0;
int currentTot = 0;
Socket socket = new Socket("localhost",16167);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do
{
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
} while(bytesRead > -1);
System.out.println("current"+currentTot);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
System.out.println("receiving first file completed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//sending file
System.out.println("sending second file started!");
File transferFile = new File ("/Users/abhishek/desktop/file2.txt");
byte [] bytearray2 = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray2,0,bytearray2.length);
OutputStream os = socket.getOutputStream();
os.flush();
os.write(bytearray2,0,bytearray2.length);
os.flush();
System.out.println("sending second file completed!");
//sending complete
socket.close();
}
}

Does the System.out.println("not moving ahead!!!");//program stucked here line actually execute? if so, then the problem is that the InputStream.read() functions are blobking functions; they will stop execution of the program ("block") until they are able to complete.
From the JavaDoc for InputStream:
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.
This method blocks until input data is available, end of file is detected, or an exception is thrown.
Since you aren't getting an exception, this means that when you call .read(), there is no data available to be read, and you program sits around waiting for data to read (that never arrives). You should check that your client program is actually sending the data in the first place.

I'd bet
bytesRead = is.read(bytearray1,0,bytearray1.length);
is where you're really getting stuck. The problem normally if you are stuck here is that the other side of the communication has not sent any data, there's nothing to read, and your thread is stuck waiting for it to send.
on your client side, you call
bos.close();
after sending the first message. This is going to cause the socket to close as well, which will throw an IOException on your server end, and because you are not catching the IOException, your server program will just exit.
How much socket experience do you have? If you are just beginning with sockets, you might want to check out the extensions I wrote around this, starting with ServerSocketEx and DataFetcher.

Related

Send and then receive file in the same socket? [Java] [duplicate]

I am sending files to remote Android client from java server. I write the bytes using outputstream. On reading these bytes read() method keep trying to read bytes after the stream is ended. if I close the outputstream on server-side, read operation work fines. But I have to write file on the same socket again so can't close output stream any solution?
NOTE: MY CODE WORKS FINE FOR SHARING SINGLE FILE
CODE FOR WRITING FILE
public static void writefile(String IP, String filepath, int port, OutputStream out) throws IOException {
ByteFileConversion bfc = new ByteFileConversion();
byte[] file = bfc.FileToByteConversion(filepath);
out.write(file, 0, file.length);
out.close(); // i donot want to close this and how can I tell reading side that stream is ended.
System.out.println("WRITTEN");
}
Here Am I reading the file on Android :
public Bitmap fileReceived(InputStream is) {
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
// System.out.println(imageInSD);
if (is != null) {
FileOutputStream fos = null;
OutputStream bos = null;
try {
bos = new FileOutputStream(imageInSD);
byte[] aByte = new byte[1024];
int bytesRead;
int index = 0;
DataInputStream dis = new DataInputStream(is);
while ((bytesRead = is.read(aByte)) > 0) {
index = bytesRead + index;
bos.write(aByte, 0, bytesRead);
// index = index+ bytesRead;
System.out.println("Loop" + aByte + " byte read are " + bytesRead + "whree index =" + index);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "out of loop");
java.io.FileInputStream in = new FileInputStream(imageInSD);
bitmap = BitmapFactory.decodeStream(in);
bitmap = BitmapFactory.decodeFile(imageInSD);
Log.i("IMSERVICE", "saved");
// if (bitmap != null)
// System.out.println("bitmap is "+ bitmap.toString());
} catch (IOException ex) {
// Do exception handling
// Log.i("IMSERVICE", "exception ");
System.out.println("ex");
}
}
return bitmap;
}
Actually, I want to reset socket connection
Thanks in advance
You need to:
Send the length of the file ahead of the file. You can use DataOutputStream.writeLong() for that, and DataInputStream.readLong() at the receiver.
Read exactly that many bytes from the stream at the receiver:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0)
{
out.write(buffer, 0, count);
total += count;
}
E&OE
Actually I want to reset socket connection
Actually you don't want to do any such thing.
If i donot close outputstream the read operation on other side stuck on keep reading
That is because the client socket's InputStream is still waiting for the server to send some packets of data thus blocking your Main Thread.
Solution:
You can put each of your sending(OutputStream) and reading(InputStream) of packets of data from the socket to a Thread to prevent blocking your main thread when reading and sending.
Create a thread that reads the InputStream and another one for the OutputStream
Side note:
Don't try to close your outputStream that it cant be reopened again as the documentation is saying:
Closing the returned OutputStream will close the associated socket.
The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

Sending a file using sockets (java) from a client to the server succeeds but the client freezes and does not exit the loop

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.

Keep Socket alive while send file

Iam sending a image from my android to pc ,its part of my app, Iam using sockets for this The sending part code includes
public void sendfile()
{
try {
System.out.println("looppppppp");
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
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);
bis.close();
OutputStream ous = socket.getOutputStream();
System.out.println("Sending...");
ous.write(mybytearray,0,mybytearray.length);
ous.flush();
//ous.close();
// socket.close();
System.out.println("send overrrrrrrrrrr");
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Socket is connected in a thread when the program starts.
The receiver is a java code in pc as follows
#Override
public void run()
{
try
{
ServerSocket servsocket = new ServerSocket(13267);
System.out.println("Thread Waiting...");
Socket socket = servsocket.accept();
System.out.println("Accepted connection : " + socket);
System.out.println("Connected..");
while(true)
{
// filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
mybytearray = new byte [filesize];
File f=new File("d:\\ab.jpg");
f.createNewFile();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
System.out.println("b4");
bytesRead = is.read(mybytearray,0,mybytearray.length);
System.out.println("after");
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
fos.close();
}
}catch(IOException e)
{
System.out.println("errorr");
}
}
}
The problem is File Does'nt appear on my pc Unless i close my output stream or socket If i close output stream the socket is getting closed why this?
Keep Socket alive while send file
Sending the file keeps the socket alive. I don't see the relevance of your title to your question.
The problem is File Does'nt appear on my pc Unless i close my output stream or socket
So close it. Closing the socket at the sender causes the receiver to exit your receive loop, which has no other way of exiting. Your stream copy loops are far more elaborate than necessary. It is neither necessary nor advisable to buffer entire files in memory before or after sending.
If i close output stream the socket is getting closed why this?
Because that's what it's specified to do. Closing the input or output stream of a socket closes the other stream and the socket.
If I understand correct you want to keep the socket open with the client, and also send files ...
My suggestion is :
- keep one main thread open to notify the server about new files
- open new threads to send each new file
- add code to control the maximum number of files that you can send at the same time (optional)
So the flow would be :
1. client open main socket
2. server open the main socket and assign a client id
3. client request the send of a new file
4. server keep in memory the file name and client id
5. server send response authorizing the client to send the file
6. client open a new thread to send the file

Sending large files over socket

I got working over socket file sender, it worked perfectly, but I couldn't send large files with it. Always got heap error. Then I changed the code of client, so it would send file in chunks. Now I can send big files, but there is new problem. Now I recieve small files empty and larger files for example videos can't be played. Here is the code of client that sends file:
public void send(File file) throws UnknownHostException, IOException {
// Create socket
hostIP = "localhost";
socket = new Socket(hostIP, 22333);
//Send file
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
OutputStream os = socket.getOutputStream();
//Sending size of file.
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName() + ":" + userName);
byte[] arr = new byte[1024];
try {
int len = 0;
while ((len = dis.read(arr)) != -1) {
dos.write(arr, 0, len);
}
} catch (IOException ex) {
ex.printStackTrace();
}
dos.flush();
socket.close();
}
and here is the server code:
void start() throws IOException {
// Starts server on port.
serverSocket = new ServerSocket(port);
int bytesRead;
while (true) {
connection = serverSocket.accept();
in = connection.getInputStream();
clientData = new DataInputStream(in);
String[] data = clientData.readUTF().split(":");
String fileName = data[0];
String userName = data[1];
output = new FileOutputStream("C:/" + fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
// Build new file
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
}
}
You failed to write out the length of the file to the stream in the client:
long size = clientData.readLong();
So that call in the server is reading the first 8 bytes of the actual file and who knows what that quantity is. You don't have to read the length from the stream since you only wrote a single file. After reading the filename, and username (not very secure is it?) you can just read the stream until EOF. If you ever wanted to send multiple files over the same open socket then you'd need to know the length before reading the file.
Also your buffers for reading are way to small. You should be at a minimum of 8192 instead of 1024. And you'll want to put all .close() in a finally block to make sure your server and clients shutdown appropriately if there is an exception ever.

Java socket transfer, buffered input and output

Ok.... Trying to learn java on my own, been having trouble with this for awhile. I'm trying to transfer a large file over the network using sockets and buffered input and output streams. Doesn't matter what size file I try to transfer. Hopefully I posted my code correctly, I know theres probably many problems with this code, although it compiles and runs ok, I get an IndexOutOfBoundsException the second the client and server go into the while loops, the server gets it during the first bis.read(buf,0,len) and the client gets it during the while(off = fis.read(buf,0,len)..... Any help would be greatly appreciated
//Server Receive code receive method and main for testing
public File receive(Socket socket) throws IOException{
//temporarily hard coded filename
File file = new File("C:\\users\\tom5\\desktop\\sales\\input.dat");
DataInputStream dis = new DataInputStream(socket.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
//reads file length from datainputstream
int len = dis.readInt();
dis.close();
int bytesRead=0;
//create buffer
byte[]buf = new byte[4092];
int off = 0;
//read from BufferedInputStream and write to FileOutputStream?
while(bytesRead < len) {
bis.read(buf,0,len);
fos.write(buf,0,len);
bytesRead++;
}
fos.close();
bis.close();
return file;
}
public static void main(String[]args) throws IOException{
Server server = new Server();
Socket socket =server.accept();
File file = server.receive(socket);
}
}
//Client sending code
public void send(Socket socket,File file) throws IOException{
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
int len = (int)file.length();
dos.writeInt(len);
dos.flush();
dos.close();
System.out.println(file.length());
byte[]buf = new byte[4092];
int off= 0;
while((off = fis.read(buf,0,len)) != -1 ){
bos.write(buf,0,len);
}
}
public static void main(String[]args) throws UnknownHostException, IOException{
Client client = new Client();
Socket socket =client.connect("localhost",1055);
File file = new File("C:\\users\\tom5\\desktop\\movie.avi");
}
}
while(bytesRead < len) {
bis.read(buf,0,len);
fos.write(buf,0,len);
bytesRead++;
}
You're trying to read len bytes into buf, which is larger than its length, and you're incrementing bytes by 1 each time even though read can read multiple bytes. It should be more like:
while(bytesRead < len) {
int n = bis.read(buf);
fos.write(buf, 0, n);
bytesRead += n;
}
or if there's the possibility of extra bytes after the file you don't want to read:
while(bytesRead < len) {
int n = bis.read(buf, 0, Math.min(buf.length, len - bytesRead));
fos.write(buf, 0, n);
bytesRead += n;
}
There is a similar problem in the write method. You're storing the return value in off but you never use it.
You are wrapping the stream twice, once as dis and once as bis. This means that dis is not buffered but when you close it, you close the underlying stream.
I suggest you wrap use ONLY
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
If you want an efficient buffer size, I suggest you a power of 2, i.e 4096 rather than 4092.
A #fgb notes: You correct use the length read() on the sending size but ignore it on the receiving size (The irony being that you usually get the size you ask for when reading a file, but not so much when reading a socket)
Consider using one common InputStream to OutputStream copier method which works in both situations e.g. like IOUtils.copy().
You are using fixed buffer size. Try this:
byte[] mybytearray = new byte[(int) myFile.length()];

Categories