将文件从服务器发送到另一个客户端(Java)时遇到问题

时间:2015-05-25 18:04:46

标签: java file sockets server

我在尝试将文件从服务器发送到另一个客户端时遇到了一些困难。 我们说我有两个客户端连接到服务器。 现在Server成功将文件发送到第一个客户端但是当服务器尝试发送到第二个客户端时,客户端没有收到它。 以下是一些代码:

服务器:

public synchronized void sendToAllClients() {
    for (Socket z : clientSockets) {
        if (z != null) {
            System.out.println("TEST");
            PrintWriter print = null;
            try {

                File myFile = new File(FILE PATH);
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);

                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);

                OutputStream os = z.getOutputStream();

                DataOutputStream dos = new DataOutputStream(os);

                dos.writeLong(mybytearray.length);
                dos.write(mybytearray, 0, mybytearray.length);
                dos.flush();


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

客户端:

public static void receiveFile(String fileName) {
        try {
            int bytesRead;
            InputStream in = sock.getInputStream();

            clientData = new DataInputStream(in);


            OutputStream output = new FileOutputStream(
                    (FILEPATH + FILENAME);
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0
                    && (bytesRead = clientData.read(buffer, 0,
                            (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }

            output.flush();

        } catch (IOException ex) {

        }
    }

0 个答案:

没有答案