I'm developing a P2P application and would like the nodes to serve as both clients and servers. For example, say that I establish a listening node with the following code running in a goroutine:
ln, _ := net.Listen("tcp", ":8080")
for {
conn, err := ln.Accept()
.....
}
Then, in another goroutine the logic has determined that it must contact another node to let it know of its existence, say on the localhost address ":8081" which also has a similar listening loop running.
If I just use net.Dial("tcp", ":8081")
, it will choose a random port number to connect from, and the node on 8081
will try to contact that port instead of the correct one on 8080
. Is there a way to initiate the net.Dial
call from 8080
? Is such a thing even allowed, or would the listener get confused and intercept the communications that were meant for the socket returned by net.Dial
?
If you are looking to control the local port when dialing out, you can use net.DialTCP