将文件发送到多个客户端

时间:2015-07-21 15:29:56

标签: java tcp client-server

我创建了一个客户端 - 服务器应用程序来交换字符串和文件。 我需要将相同的文件发送到所有客户端,但只有第一个客户端接收该文件。我注意到有趣的是,当第一个客户端收到文件,我在文件系统上打开并关闭该文件时,第二个客户端会收到该文件。

服务器端,发送文件:

private static void sendFile(String path, OutputStream os) throws IOException {

    File file = new File(path);
    byte[] toSent  = new byte [(int)file.length()];

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(toSent, 0, toSent.length);

    os.write(toSent);
    os.flush();

    bis.close();

}

客户端,接收文件:

private static void receiveFile(String path, InputStream is){
    int bytesRead = 0;
    byte [] toRecieve  = new byte [2048];

    try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) {

        bytesRead = is.read(toRecieve, 0, toRecieve.length);

        bos.write(toRecieve, 0, bytesRead);

        bos.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } 
}

ServerThread类中的OutputStream对象的定义(扩展Thread):

Socket socket;
BufferedReader in;
PrintWriter out;
OutputStream os;
InputStream is;

public ServerPricaloThread(Socket socket) {
    super();
    this.socket = socket;

    try {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
        os = socket.getOutputStream();
        is = socket.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.start();
}

服务器类:

public class Server {

private static final int TCP_PORT = 9000;

public static void main(String[] args) {

    ServerSocket ss = null;
    Socket socket = null;

    try {

        File file = new File("server/online.txt"); 
        file.delete();

        ss = new ServerSocket(TCP_PORT);
        while(true) {
            socket = ss.accept();
            new ServerThread(socket);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

0 个答案:

没有答案