Link to home
Start Free TrialLog in
Avatar of shoooot
shoooot

asked on

Passing files through sockets...

Hi,
I want to pass some files, from one machine to another via socket system.
My questions is, how to read and pass the files?
Reading the file and storing it in an array of bytes, and then serializing this array?

There is another way to do that more clean?

Thx
MARC
Avatar of daitt
daitt
Flag of Viet Nam image

Hello, you can write something like this:

//Sending
byte[] buf = new byte[1024];
int length = fileinputstream.read(buf);
while (length > 0){
   socketoutputstream.write(buf,length);
   length = fileinputstream.read(buf);
}

//Receiving
byte[] buf = new byte[1024];
int length = socketinputstream.read(buf);
while (length > 0){
   fileoutputstream.write(buf,length);
   length = socketinputstream.read(buf);
}
Avatar of Venci75
Venci75

try this:
// sending a file:

FileInputStream in = new FileInputStream("myFile");
byte[] buffer = new byte[2048];
Socket s = new Socket("localhost", 12345);
OutputStream out = s.getOutputStream();
int r;
while ((r = in.read(buffer)) != -1)
  out.write(buffer, 0, r);

out.flush();
out.close();


// receiving the file:

FileOutputStream out = new FileOutputStream("myFile");
byte[] buffer = new byte[2048];
Socket s = (new ServerSocket(12345)).accept;
InputStream in = s.getInputStream();
int r;
while ((r = in.read(buffer)) != -1)
  out.write(buffer, 0, r);

out.flush();
out.close();
ASKER CERTIFIED SOLUTION
Avatar of gadio
gadio

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial