Java nio establishes lots of connections, How to do a count?
+2
A:
Add 1 to a variable every time you accept a connection, and decrement it every time you close one.
Is this a trick question? ;-)
EJP
2010-03-08 05:23:32
Simple to say...
bruce dou
2010-03-08 05:34:19
...simple to implement. Wherever you have your select() loop, check to see which branch accepts the connection and increment there.
Malaxeur
2010-03-08 05:49:43
@bruce dou - There is no way to do this apart from implementing a counter as suggested by @EJP.
Stephen C
2010-03-08 05:59:31
@bruce dou: simple to say and trivial to do, hence my comment, unless of course your NIO code is complete spaghetti, which I can't do anything about.But why do you need to know? I have written quite a number of production java.net and java.nio servers without ever needing a count of connected clients.@Stephen C: there is actually another way via Selector, assuming you are using a Selector for all channels, and assuming you know how many ServerSocketChannels you have, or that you're prepared to traverse a data structure.
EJP
2010-03-08 06:49:02