使用java.io的非阻塞服务器

编程入门 行业动态 更新时间:2024-10-23 21:40:00
本文介绍了使用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中没有select(),因此您可以简化为轮询套接字,这意味着在两次轮询之间睡眠,并且您无法告知睡眠时间,因此您的睡眠时间将超过必要的时间,因此您将浪费时间,增加等待时间等;否则,您必须短暂地睡眠,以免消耗无用的CPU.

It is possible but pointless. There is no select() in java, 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的非阻塞服务器

本文发布于:2023-11-25 09:02:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器   java   io

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!