I'm studying Go for network programming. The problem is Go documentation is too simple. For example, I don't know when to use net.DialTCP
, and when to use TCPListener
object to AcceptTCP
, what's the difference? How about client communicate with another client? Not client to server.
In Go, you use the Dial
function from net
to connect to a remote machine.
net.Dial("tcp","google.com:80")
net.Dial("udp","tracker.thepiratebay.org:6969")
net.Dial("ip","kremvax.su")
net.Dial("unix","/dev/log")
This gives you an abstract Conn
object that represents the connection you just established. Conn
implements the ReadWriteCloser
interface from io
and a couple of other functions. You can use this object to send and receive data.
To listen, i.e. open a port, you use the Listen
function from net. Calling Listen
gives you a Listener
object. Use Accept
to accept incoming connections. Accept
returns another Conn
object that can be used as above.
ls, err := net.Listen("tcp",":1337")
if err != nil {
// port probably blocked, insert error handling here
}
conn, err := ls.Accept()
if err != nil {
// error handling
}
conn.Write("Hello, world!")
These functions give you more control over TCP connections. I suggest you to only use them if they are definitly needed for your program as Dial
and Listen
are simpler, more generic and easily allow you to adapt your program to other types of network connections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With