[英]Sending multiple files in java callback?
How can I add to the sending queue, for example I choose a file with JFileChooser and then send it in a new thread to the client, and I want to choose another and send it as well. 如何添加到发送队列中,例如,我使用JFileChooser选择了一个文件,然后在新线程中将其发送到客户端,并且我想选择另一个并发送它。 What happens is that it sends the files simultaneously and the output on the client side is broken.
发生的情况是它同时发送文件,并且客户端的输出中断。
I'd like to be able to add to a "queue" of some sort, so that when the first file is sent, the server will start sending the next one. 我希望能够添加某种“队列”,以便在发送第一个文件时,服务器将开始发送下一个文件。
A good aproach for socket communication
between server->client, is to have 1 thread per client and have this thread reading from a java.util.concurrent.BlockingQueue
. 在服务器->客户端之间进行
socket communication
一个很好的方法是,每个客户端有1个线程,并从java.util.concurrent.BlockingQueue
读取该线程。 Such interface is ideal (just like all the java.util.concurrent objects) for managing multithreading concurrency. 这样的接口是管理多线程并发的理想选择(就像所有java.util.concurrent对象一样)。
The idea, is that the Server has a ClientThread
like this: 这个想法是,服务器具有如下所示的
ClientThread
:
class BroadCastThread extends Thread{
LinkedBlockingQueue<SendFileTask> bcQueue = new LinkedBlockingQueue<>();
@Override
public void run() {
while( true ){
try {
SendFileTask task = bcQueue.take();
task.sendFile();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
void addTask(SendFileTask rt) throws InterruptedException{
bcQueue.put(rt);
}
}
interface SendFileTask{
void sendFile() throws Exception;
}
And use this by adding tasks
to you thread object: 并通过
adding tasks
线程对象adding tasks
来使用它:
BroadCastThread bct = new BroadCastThread();
bct.start();
//With lambda
bct.addTask(() -> {
//Send file code
});
//Without lambda
bct.addTask(new SendFileTask() {
@Override
void sendFile() throws Exception {
//Send file code
}
});
You can even store the Socket information with the thread, and pass it throw the task interface, if you want the sendFile
method to receive it as parameter. 如果您想让
sendFile
方法将其作为参数接收,甚至可以将Socket信息与线程一起存储,并传递给任务接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.