0
請你看看我的代碼:java.nio.SocketChannel總是返回相同的數據
private void initSocket() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.bind(null);
socketChannel.connect(new InetSocketAddress(host,port));
while(! socketChannel.finishConnect()){
Thread.sleep(5);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initOutput() {
outBuffer = ByteBuffer.allocateDirect(512); //Allocate direct for better performance (no java-heap alloc)
outBuffer.clear();
}
private void initInput() {
inBuffer = ByteBuffer.allocateDirect(1024); //Allocate direct for better performance (no java-heap alloc)
inBuffer.clear();
}
public String in() {
try {
while (socketChannel.re)
socketChannel.read(inBuffer);
inBuffer.mark();
final String ret = Charset.forName("UTF-8").newDecoder().decode(inBuffer).toString();
bulletin.PIPE_IN.Info.push(" <<< ", new String[]{"TsPipe2","in"}, new Object[]{ret, inBuffer});
return ret;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void out (String out) {
outBuffer.clear();
outBuffer.put(out.getBytes());
//Write all in one go
bulletin.PIPE_OUT.Info.push(" >>> ", new String[]{"TsPipe2","out"}, new Object[]{outBuffer, out});
int toWrite = outBuffer.remaining();
for (int i = 0; i < toWrite; ++i) {
try {
i += socketChannel.write(outBuffer);
Thread.sleep(Period.NIO_CHANNEL_WRITE_SLEEP.getValue());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
並告訴我,我究竟做錯了什麼?
正如標題所言,我總是從在法得到相同的數據,我不確信閹我出方法的工作或不
我現在走過throught幾個教程,它可能是我混的東西了。 我也發現有前途的東西在stackoverflow - 但沒有任何工作。
作爲一個小的背景信息 - 我正在寫一個Teamspeak機器人通過套接字與TS服務器通信,並已走得很遠。從我第一次聽說nio的那一刻起,我想遷移到它。
他們的其他框架是否需要考慮?聽說Google Grizzly很整潔,但不知道它對我的情況有用嗎?
你在哪裏清除緩衝區?我建議你改變你的代碼來一次處理部分讀取和多個消息。 TCP是一個流協議,而不是一個消息協議。 –