使用java.io的非阻塞服务器 [英] A non-blocking server with java.io

查看:68
本文介绍了使用java.io的非阻塞服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都知道Java IO是 blocking ,而Java NIO是 non-blocking .在IO中,每个客户端模式必须使用线程,在NIO中,所有客户端都可以使用一个线程.

Everybody knows that java IO is blocking, and java NIO is non-blocking. In IO you will have to use the thread per client pattern, in NIO you can use one thread for all clients.

现在我的问题是:是否可以使用 only Java IO API进行非阻塞设计. (不是NIO)

Now my question follows: is it possible to make a non-blocking design using only the Java IO api. (not NIO)

我正在考虑这样的模式(显然非常简单);

I was thinking about a pattern like this (obviously very simplified);

        List<Socket> li;
        for (Socket s : li) {
            InputStream in = s.getInputStream();
            byte[] data = in.available();
            in.read(data);
            // processData(data); (decoding packets, encoding outgoing packets
        }

还请注意,客户端将始终准备就绪,可以读取数据.

您对此有何看法?这是否适合至少应拥有数百个客户端且没有重大性能问题的服务器?

What are your opinions on this? Will this be suitable for a server that should at least hold a few hundred of clients without major performance issues?

推荐答案

可能,但毫无意义. java.net中没有select(),因此您可以简化为轮询套接字,这意味着在两次轮询之间睡眠,并且您无法告知睡眠时间,因此您的睡眠时间将超过必要的时间,因此您将浪费时间,增加等待时间等;否则,您必须短暂地睡眠,以免消耗无用的CPU.

It is possible but pointless. There is no select() in java.net, so you are reduced to polling the sockets, which implies sleeping between polls, and you can't tell how long to sleep for, so you will sleep for longer than necessary, so you will waste time, add latency, etc; or else you must sleep for stupidly short intervals and so consume pointless CPU.

对于仅有几百个客户端的人,没有可能反对每个连接使用常规线程.

For a mere few hundred clients there is no possible objection to the conventional use of a thread per connection.

我不知道客户端将永远准备好读取数据"是什么意思.您无法从服务器上得知这一点,如果还没有准备好,它的写入可能会阻塞,这将彻底破坏您的applecard.

I don't know what 'the client will always be ready for reading data' means. You can't tell that from the server, and if it isn't ready, writes to it can block, which will upset your applecard completely.

这篇关于使用java.io的非阻塞服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆