Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network programming in Go

Tags:

go

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.

like image 247
Pole_Zhang Avatar asked Dec 05 '22 08:12

Pole_Zhang


1 Answers

Connecting

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.

Listening

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!")

DialTCP and ListenTCP

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.

like image 177
fuz Avatar answered Dec 24 '22 15:12

fuz