我使用的SocketChannel像這樣單個連接:如何在Java中使用套接字進行快速數據讀取?
int sampleBufferSize = 50;
StringBuilder data = new StringBuilder();
ByteBuffer bf = ByteBuffer.allocate(sampleBufferSize);
SocketChannel sc = new SocketChannel();
while(true)
if(sc.read(bf) > 0){
bf.flip();
while(bf.hasRemaining())
data.append((char) bf.get());
bf.clear();
}else{
fireDataReceived(data.toString());
data.delete(0, data.length());
}
此代碼是不是很有效,但它從0.05秒同一PC讀取HTTP POST請求130 KB。現在我正在嘗試編寫一個類似功能但使用Socket的類。下面是代碼:
private static final int TIMEOUT_MILLIS = 50;
private boolean reading = false;
private long readBeginTime = 0;
private StringBuilder buffer = new StringBuilder();
private Thread thread = new Thread(){
public void run(){
while(!isInterrupted()){
try {
int b = getInputStream().read();
if(b == -1){
if(reading)
fireDataReceived();
close();
}else{
if(!reading){
reading = true;
readBeginTime = System.currentTimeMillis();
setSoTimeout(TIMEOUT_MILLIS);
}
buffer.append((char) b);
}
} catch (SocketTimeoutException e){
fireDataReceived();
} catch (IOException e) {
e.printStackTrace();
if(reading)
fireDataReceived();
close();
}
}
}
};
private void fireDataReceived(){
BufferedSocketEvent e = new BufferedSocketEvent(this, System.currentTimeMillis() - readBeginTime, buffer.toString());
buffer.setLength(0);
reading = false;
try {
setSoTimeout(0);
} catch (SocketException e1) {
e1.printStackTrace();
}
for(BufferedSocketListener listener: listeners)
listener.dataReceived(e);
}
而問題是,它需要0.4秒同一請求,我不知道爲什麼要花這麼長。請解釋我的代碼有什麼問題。
'TIMEOUT_MILLIS = 50'爲什麼會超時如此之小:
我會是這樣的開始?在互聯網上延遲50毫秒並不罕見。 –
@Banthar,這是一個例子。我已經在一臺PC的範圍內進行了測試。對於本地主機來說,這是一個巨大的超時 –
如果將其設置爲30秒,您的程序是否工作得更慢? –