繁体   English   中英

java.nio.SocketChannel总是返回相同的数据

[英]java.nio.SocketChannel always returning the same data

你能看看我的代码吗?

    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) while循环中缺少一些括号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM