首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java.nio.SocketChannel总是返回相同的数据

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

Stack Overflow用户
提问于 2013-11-24 02:42:46
回答 1查看 89关注 0票数 0

你能看一下我的代码吗:

代码语言:javascript
复制
    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机器人,并且已经走得相当远了。从我第一次听说nio的那一刻起,我就想迁移到它。

他们的其他框架需要考虑吗?听说Google Grizzly相当整洁,但不确定它对我的情况是否有用?

EN

回答 1

Stack Overflow用户

发布于 2013-11-24 02:47:49

我相信你在这个while (socketChannel.re)循环中遗漏了一些花括号。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20166332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档