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();
}
}
}
}
告诉我我做错了什么?
正如主题所述,我总是从in-method获取相同的数据,并且我不确定我的out-method是否有效
我现在经历了几个教程,可能是我混淆了一些东西。 我还在stackoverflow上找到了有希望的东西 - 但是没有任何工作。
作为一个小背景信息 - 我正在通过带有TS-Server的套接字编写Teamspeak bot communicatin并且已经走得很远了。从我第一次听说有关nio的那一刻起,我就想迁移到它。
他们的其他框架需要考虑吗?听说Google Grizzly非常整洁,但不确定它对我的情况有用吗?
答案 0 :(得分:1)
我相信你在这个while (socketChannel.re)
循环中错过了一些大括号。