Multiple channels on same port

Why wont java.nio let me open several channels on the same port?

Nice open question :slight_smile:

If you mean open a completely new channel, its because the channel is associated with a socket. In UDP and TCP you can only have one socket bound to any port (note UDP and TCP are independant of each other tho).

Kev

Hmm, then how can I accept multiple connections on the same port? Must I use the “main” port as control channel and tell the clients where to connect next? Doesnt make much sense, dont see why many channels shouldnt be able to bind the same port :slight_smile: The connections can still be identified.

Channels exist within sockets, however, you can only really have 2 channels per socket (1 in, 1 out). Sockets can not be bound to the same port.

You accept connections on the same port in TCP, but it then allocated a new socket/channel locally (under the hood) which you use to communicate with the client.

With UDP you can send and recieve to/from which ever address you like using the same port, just as long as you don’t call connect(). However, this can be quite slow (using one channel for all comms).

Channels can’t bind to anything, sockets bind. Sockets can’t bind to the same port. How would the Operating System know who to deliver packets to? e.g. 2 applications came up, both bind to port 3000 using TCP. A packet arrives at the machine for port 3000 using TCP, which application do you deliver it to? both? neither? choose a random one?

Equally, you couldn’t identify the source of a packet fully without having a fully qualified (port included) at the other end of the socket.

Kev

Then how would I do it “under the hood” ? For example, consider a telnet server… It lets clients connect and then what? As far as I know the telnet client can´t be told to connect to another port on the server, and it would also complicate it all with firewall etc…

The socket created locally doesn’t have a port, its actually just a file descriptor that allows packets to be recieved and sent.

When you do…

ServerSocket s = new ServerSocket(1000);
Socket newConnection = s.accept();

The newConnection socket is wrapped round the file descriptor that is passed back from the listening socket. However, its a completely seperate channel and file descriptor. It doesn’t have to send anything back to the other end since at the TCP layer recieved packet is sent to the right FD.

Outgoing connections always need their own port.

Kev

Kev

Ahh, wow, I didnt know that :slight_smile: So I can basically have one ServerSocketChannel running and create new SocketChannels from that one with accept() , and after that I dont have to create any new ServerSocketChannels to get new connections?

Btw thanks for taking time and helping me out :slight_smile:

Yep, one server socket, lots of connected people…

Not a problem btw, its what makes the community really cool…

Kev

:slight_smile: Thanks for discussing this, it was very helpful.