我一直在使用this教程来实现一个使用socket IO的简单文件传输客户端/服务器。我更改了响应处理程序,将多个读取作为一个文件的一部分接受,因为我将处理大文件,可能高达500MB。本教程没有考虑到大型服务器响应,所以我有点挣扎,并且我创建了一个竞争条件。
下面是响应处理程序代码:
public class RspHandler {
private byte[] rsp = null;
public synchronized boolean handleResponse(byte[] rsp) {
this.rsp = rsp;
this.notify();
return true;
}
public synchronized void waitForResponse() {
while(this.rsp == null) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
System.out.println("Received Response : " + new String(this.rsp));
}
public synchronized void waitForFile(String filename) throws IOException {
String filepath = "C:\\a\\received\\" + filename;
FileOutputStream fos = new FileOutputStream(filepath);
while(waitForFileChunk(fos) != -1){}
fos.close();
}
private synchronized int waitForFileChunk(FileOutputStream fos) throws IOException
{
while(this.rsp == null) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
fos.write(this.rsp);
int length = this.rsp.length;
this.rsp = null;
if(length < NioClient.READ_SIZE)//Probably a bad way to find the end of the file
{
return -1;
}
else
{
return length;
}
}
}程序的主线程在主线程上创建一个RspHandler,并将其传递给在单独线程上创建的客户端。主线程告诉客户端请求一个文件,然后告诉RspHandler侦听响应。当客户端从服务器读取数据时(它现在读取的块大小约为1KB ),它调用handleResponse(byte[] rsp)方法,填充rsp字节数组。
从本质上讲,我不会将接收到的数据以最快的速度写入文件。我对线程还是个新手,所以我不知道该怎么做才能摆脱这种竞争状况。有什么提示吗?
发布于 2012-01-11 01:44:59
这是典型的消费者/生产者。处理此问题的最直接/最简单的方法是使用BlockingQueue。生产者调用put(),消费者调用take()。
注意,使用BlockingQueue通常会导致“如何完成”的问题。要做到这一点,最好的方法是使用“毒丸”方法,生产者在队列上粘贴一个“特殊”值,该值向消费者发出没有更多数据的信号。
https://stackoverflow.com/questions/8807551
复制相似问题