Sending files without closing the socket output

Hi all!

I'm new to sockets, and I'm trying to get a file from a Server...the problem is that unless I close the socket output stream the Client will hang...

Here is the code:

Client

publicclass FileClient{

publicstaticvoid main(String[] args){

try{

Socket socket =new Socket(InetAddress.getLocalHost(), 9192);

ObjectInputStream in =new ObjectInputStream(socket.getInputStream());

FileOutputStream fos =new FileOutputStream("result.txt");

System.out.println("Downloading file...");

byte[] buf =newbyte[4096];

while(true){

int len = in.read(buf);

if(len == -1)break;

fos.write(buf, 0, len);

}

fos.flush();

fos.close();

System.out.println("Done.");

}catch(Exception e){ e.printStackTrace();}

}

}

Server

publicclass FileServer{

publicstaticvoid main(String[] args){

try{

ServerSocket ss =new ServerSocket(9192);

while(true){

System.out.println("Wating for connection...");

Socket socket = ss.accept();

OutputStream out =new ObjectOutputStream(socket.getOutputStream());

String fileName ="Stuff/result.txt";

System.out.println("Sending file...");

FileInputStream fis =new FileInputStream(fileName);

byte[] buf =newbyte[4096];

while(true){

int len = fis.read(buf);

if(len == -1)break;

out.write(buf, 0, len);

}

fis.close();

System.out.println("Done.");

}

}catch (Exception ex){

ex.printStackTrace();

}

}

}

Is there a way to solve this without closing the output stream? And if I do close the socket output stream, is there any problem in opening it again?

Thanks in advance

[3838 byte] By [bronze-starDukes] at [2007-11-26 12:13:34]
# 1

If you want to send more than one file down the same socket you'll have to send the file length first so the receiver knows when the file stops.

Closing the outputstream or the inputstream of a socket closes the socket.

You don't need ObjectInput/OutputStreams for this: change them to BufferedInput/OutputStreams. OOS adds a header which you don't need unless you're transmitting objects.

platinumsta at 2007-7-7 14:15:01 > top of Java-index,Archived Forums,Socket Programming...
# 2
This is just a sample of what I'm trying to do...In the original program this is part a thread...And I need ObjectOutputStream to send some objects, that's why I'm using it..I'll try as you say, sending the file length..Thanks
bronzestar at 2007-7-7 14:15:01 > top of Java-index,Archived Forums,Socket Programming...