通过套接字发送多个文件。文件数量未知

时间:2015-05-17 16:11:50

标签: java file sockets

我正在制作一个能够发送文件的沟通者。 到目前为止,我设法使用额外的线程(监听器)使文本发送工作。

我正在尝试用文件做同样的事情,但我不知道,我怎么能创建一个文件监听器 - 一个线程,它检测传入的文件,下载它并侦听另一个文件。此外,我不知道我是否正确地使我的文件发送者。你能帮忙吗?

当前发件人代码:

try {
    InputStream in = new FileInputStream(fileToSend);
    OutputStream out = fileConn.getOutputStream();
    Controller.copyData(in, out);
    out.close();
    in.close();
} catch (IOException e) {
    System.out.println("Problem!");
}

接收者代码:

while (true)
{
    try {
        InputStream in = socket.getInputStream();
        OutputStream out = new FileOutputStream("hi.txt"); //temporary
        Controller.copyData(in, out);
        out.close();
        in.close();
    } catch (IOException e) {
        System.out.println("Problem!");
    }
}
编辑:我忘了添加我的copyData。那是:

public static void copyData(InputStream in, OutputStream out) throws IOException{
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len);
    }
}

1 个答案:

答案 0 :(得分:-1)

您可以通过添加到您的侦听线程选项来等待不同的消息/选项并做出相应的反应。例如:

private class WaitingThread extends Thread {
    volatile boolean awaitsServer = false;
    DataInputStream dataInput = new DataInputStream(inputStream);
    public void run() {
        while (connected) {
            int message = 0;
                if (awaitsServer == true) {
                    if (dIn.available() ==0) {
                        view.setLog("waiting");
                    } else {
                        message = dIn.readInt();
                        switch (tempMessage) {
                        // TO DO ALL KIND OF COMMUNICATION 

                        case 1: 
                            int filesize = dataInput.readInt();
                            int bytesRead;
                            int currentTot = 0;
                            byte[] bytearray = new byte[filesize];
                            int len = dataInput.readInt();
                            FileOutputStream fos = new FileOutputStream(currentlySelectedFile);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bytesRead = dataInput.read(bytearray, 0, bytearray.length);

                    currentTot = bytesRead;
                    do {
                        bytesRead = dataInput.read(bytearray, currentTot,
                                (len - currentTot));
                        if (bytesRead >= 0)
                            currentTot += bytesRead;

                    } while (currentTot < len);
                    bos.write(bytearray, 0, currentTot);
                    bos.close();

                    }
                                case 2: //GET TEXT
                                case 3: //DO SOMETHING ELSE
}}}

顺便提一下如何发送文件。