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:33]
# 1

> 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...

> 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?

You can use a protocol like HTTP to send/receive the file. Essentially, you can use the "Content-Length" header to determine how many bytes to read from the input stream. This also makes it easy to keep the connection open and save the overhead of establishing another connection.

bronzestar at 2007-7-7 14:14:59 > top of Java-index,Archived Forums,Socket Programming...