tags:

views:

121

answers:

1

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
Simple to say...
bruce dou
...simple to implement. Wherever you have your select() loop, check to see which branch accepts the connection and increment there.
Malaxeur
@bruce dou - There is no way to do this apart from implementing a counter as suggested by @EJP.
Stephen C
@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