Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sockets - Send a file from the Client to the Server

I've seen a lot of examples for sending a file from the Server to the Client. For example (found here):

Server:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws IOException {
    ServerSocket servsock = new ServerSocket(123456);
    File myFile = new File("s.pdf");
    while (true) {
      Socket sock = servsock.accept();
      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
      bis.read(mybytearray, 0, mybytearray.length);
      OutputStream os = sock.getOutputStream();
      os.write(mybytearray, 0, mybytearray.length);
      os.flush();
      sock.close();
    }
  }
}

Client:

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class Main {
  public static void main(String[] argv) throws Exception {
    Socket sock = new Socket("127.0.0.1", 123456);
    byte[] mybytearray = new byte[1024];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("s.pdf");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
    bos.close();
    sock.close();
  }
}

Is there a way to rewrite this, or something similar, to be used the other way around, so that the Client can send the file to the Server instead?

like image 383
ricgeorge Avatar asked Feb 20 '13 10:02

ricgeorge


1 Answers

Yes, it can be done. For the client, instead of requesting the file from the server, you will read the file locally and write to the outpustream of the server. On the server side, you will accept new connections, and read from the server Inpustream what the client has sent.

like image 95
Dimitri Avatar answered Sep 19 '22 19:09

Dimitri