How to associate a local port with a socket channel

P

P. Ajay Prakash

Hi,
I am currently facing a problem programming with the
SocketChannel class of java.nio.channels package. Actually, I am
interested in non-blocking I/O for which i have to register socket
channels with a selector object. Now, in my application, i have to
associate each socket channel with a port number.
(this has to be done at channel creation time). How do i embed LOCAL
port information with my socket channel?

Could anyone please help me out with this one?

regards,
Ajay
 
S

Sudsy

P. Ajay Prakash said:
Hi,
I am currently facing a problem programming with the
SocketChannel class of java.nio.channels package. Actually, I am
interested in non-blocking I/O for which i have to register socket
channels with a selector object. Now, in my application, i have to
associate each socket channel with a port number.
(this has to be done at channel creation time). How do i embed LOCAL
port information with my socket channel?

It's important to understand the socket semantics. If I create an
outgoing TCP port then I don't specify the port number. Only with
an incoming TCP port can I "bind" to a specific port. So look at
the ServerSocketChannel.
Here's some code I dug out of one of my projects:

ServerSocketChannel serverSockChannel = null;
ServerSocket serverSock = null;
SocketChannel acceptSock = null;
Selector selector = null;
ArrayList sockets = new ArrayList();
int portNum = 11111;
try {
serverSockChannel = ServerSocketChannel.open();
serverSock = serverSockChannel.socket();
serverSock.bind( new InetSocketAddress( "localhost",
portNum ), 5 );
selector = selector.open();
serverSockChannel.configureBlocking( false );
registerSelections( selector, serverSockChannel,
sockets );
}
catch( IOException e ) {
...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top