在Java Socket编程中从多个客户端向单个服务器发送文件

时间:2014-01-17 17:09:16

标签: java sockets

您好我正在尝试在java中创建一个程序,用于将文件从多个客户端发送到单个服务器。这有可能吗?

我试过这可以用于多个客户端和单个服务器,也是从服务器到客户端发送程序。

客户计划

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


     }


}

它是我正在进行的项目的代码的一部分。

任何人都会帮忙。

1 个答案:

答案 0 :(得分:3)

你想要这样的东西:

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

其中MyThread是扩展Thread类的您的类,接受与刚连接的客户端的连接,然后接受发送给它的任何文件或数据。