Search code examples
javasocketsp2pserversocketbittorrent

How can I initiate 2 Java Sockets that listen on the same port?


I am currently writing a BitTorrent client and from my understanding I can use a single local port to connect to different peers and communicate with them independently.

If I were to write a server, i.e. I would have to accept connections then I know I could use a Java ServerSocket to listen on the same port and handle connections independently otherwise. However, what I want to do however is to initiate connections rather than waiting for them to be initiated (as there is no server), and I want to use the same local port for these (so I can connect to say hundreds of peers sharing the same port). How can I correctly do this?


Solution

  • With a socket connections, you need to have an "initiator" (usually referred to as Client) and "acceptor" (referred to as Server), even in the case of peer-to-peer communications. That is, you can still talk about Client and Server as the roles of the different peers for this particular connection.

    You can indeed reuse the local port when you act as the client (use this constructor: http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html#Socket(java.net.InetAddress,%20int,%20java.net.InetAddress,%20int) ). A socket will be created (identified by Remote Address + Remote Port + Local Address + Local Port) as long as there is no other socket with the same 4 attributes (that is, you will not be able to establish a second connection to the same peer/server, but you can establish connections to other peers with the same local port).

    I cannot think of a practical benefit of doing this though (as opposed to letting the system assign a random local port for you). Then again, there may be something I am not thinking of :)