你能看看我的代码吗?

    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();
            }
        }
    }
}


告诉我我在做什么错?

正如主题所述,我总是从方法中获取相同的数据,并且不确定我的方法是否有效

我现在浏览了一些教程,可能是我混淆了一些东西。
我还在stackoverflow上找到了有前途的东西-但是什么都没用。

作为一点背景信息-我正在编写一个通过TS-Server通过Sockets进行Teamspeak bot communicatin的程序。从我第一次听说nio的那一刻起,我就想迁移到它。

是否要考虑其他框架?听说Google Grizzly非常简洁,但不确定它对我的情况是否有用?

最佳答案

我相信您在此while (socketChannel.re)循环中缺少一些括号。

10-01 06:32