简体   繁体   中英

File sending from multiple client to Single server in Java Socket Programming

hi i am trying to create a program in java for sending files from multiple client to single server. is this is possible?

i tried this could for multiple client and single server and also it is from server to client sending program.

Client Program

public class Client {

    public Client(String ip,String path,int i) throws IOException {

        int filesize=2022386;
        int bytesRead;
        int currentTot = 0;

        File file=new File(path);
        File dir=new File("c:/PAMR/Dest"+i+"/");
        String name=file.getName();

        if(!dir.exists())
        {
            dir.mkdir();
        }

        Socket socket = new Socket(ip,9100);
        byte [] bytearray  = new byte [filesize];
        InputStream is = socket.getInputStream();


        FileOutputStream fos = new FileOutputStream(dir+"/"+name);

        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);


        bos.write(bytearray, 0 , currentTot);
        bos.flush();
        bos.close();
        socket.close();

    }



}

for Server

public class Source {


    public  Source(String path) throws IOException {

           ServerSocket serverSocket = new ServerSocket(9100);
           System.out.println("Server is in Listening Mode");
           Socket socket = serverSocket.accept();

           File transferFile = new File (path);

           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();



           os.write(bytearray,0,bytearray.length);
           bin.close();
           os.close();
           os.flush();
           socket.close();
           serverSocket.close();


     }


}

it is a part of code for my project i am doing.

Any body pls help.

You want something like this:

boolean working = true;
ServerSocket ss = new ServerSocket(9100);
while(working) {
        Socket s = ss.accept();
        MyThread myThread = new MyThread(s);
        myTread.start();
}

where MyThread is a class of yours that extends the Thread class, accepts the connection to the client that just connected and then accepts any file or data sent to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM