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.
net.DialTCP
is used on the client side to create a connection to remote server.
net.TCPListener.AcceptTCP
is used on the server side to accept new connection (possibly initiated by net.DialTCP
if client is written in Go). Note that listener may accept multiple connections, one by one, thus serving multiple clients at once (e.g. each in different goroutine).
Depending on whether you are writing client or server, you use net.DialTCP
or net.TCPListener
Maybe you should learn about network programming in general first? Then these would make more sense I think.