8.1 Sockets

Some network application developers say that the lower application layers are all about socket programming. This may not be true for all cases, but many modern web applications do indeed use sockets to their advantage. Have you ever wondered how browsers communicate with web servers when you are surfing the internet? Or How MSN connects you and your friends together in a chatroom, relaying each message in real-time? Many services like these use sockets to transfer data. As you can see, sockets occupy an important position in network programming today, and we’re going to learn about using sockets in Go in this section.

What is a socket?

Sockets originate from Unix, and given the basic “everything is a file” philosophy of Unix, everything can be operated on with “open -> write/read -> close”. Sockets are one implementation of this philosophy. Sockets have a function call for opening a socket just like you would open a file. This returns an int descriptor of the socket which can then be used for operations like creating connections, transferring data, etc.

Two types of sockets that are commonly used are stream sockets (SOCK_STREAM) and datagram sockets (SOCK_DGRAM). Stream sockets are connection-oriented like TCP, while datagram sockets do not establish connections, like UDP.

Socket communication

Before we understand how sockets communicate with one another, we need to figure out how to make sure that every socket is unique, otherwise establishing a reliable communication channel is already out of the question. We can give every process a unique PID which serves our purpose locally, however that’s not able to work over a network. Fortunately, TCP/IP helps us solve this problem. The IP addresses of the network layer are unique in a network of hosts, and “protocol + port” is also unique among host applications. So, we can use these principles to make sockets which are unique.

8.1. Sockets - 图1

Figure 8.1 network protocol layers

Applications that are based on TCP/IP all use socket APIs in their code in one way or another. Given that networked applications are becoming more and more prevalent in the modern day, it’s no wonder some developers are saying that “everything is about sockets”.

Socket basic knowledge

We know that sockets have two types, which are TCP sockets and UDP sockets. TCP and UDP are protocols and, as mentioned, we also need an IP address and port number to have a unique socket.

IPv4

The global internet uses TCP/IP as its protocol, where IP is the network layer and a core part of TCP/IP. IPv4 signifies that its version is 4; infrastructure development to date has spanned over 30 years.

The number of bits in an IPv4 address is 32, which means that 2^32 devices are able to uniquely connect to the internet. Due to the rapid develop of the internet, IP addresses are already running out of stock in recent years.

Address format:127.0.0.1, 172.122.121.111.

IPv6

IPv6 is the next version or next generation of the internet. It’s being developed for solving many of the problems inherent with IPv4. Devices using IPv6 have an address that’s 128 bits long, so we’ll never need to worry about a shortage of unique addresses. To put this into perspective, you could have more than 1000 IP addresses for every square meter on earth with IPv6. Other problems like peer to peer connection, service quality (QoS), security, multiple broadcast, etc., are also be improved.

Address format: 2002:c0e8:82e7:0:0:0:c0e8:82e7.

IP types in Go

The net package in Go provides many types, functions and methods for network programming. The definition of IP as follows:

  1. type IP []byte

Function ParseIP(s string) IP is to convert the IPv4 or IPv6 format to an IP:

  1. package main
  2. import (
  3. "net"
  4. "os"
  5. "fmt"
  6. )
  7. func main() {
  8. if len(os.Args) != 2 {
  9. fmt.Fprintf(os.Stderr, "Usage: %s ip-addr\n", os.Args[0])
  10. os.Exit(1)
  11. }
  12. name := os.Args[1]
  13. addr := net.ParseIP(name)
  14. if addr == nil {
  15. fmt.Println("Invalid address")
  16. } else {
  17. fmt.Println("The address is ", addr.String())
  18. }
  19. os.Exit(0)
  20. }

It returns the corresponding IP format for a given IP address.

TCP socket

What can we do when we know how to visit a web service through a network port? As a client, we can send a request to an appointed network port and gets its response; as a server, we need to bind a service to an appointed network port, wait for clients’ requests and supply a response.

In Go’s net package, there’s a type called TCPConn that facilitates this kind of clients/servers interaction. This type has two key functions:

  1. func (c *TCPConn) Write(b []byte) (n int, err os.Error)
  2. func (c *TCPConn) Read(b []byte) (n int, err os.Error)

TCPConn can be used by either client or server for reading and writing data.

We also need a TCPAddr to represent TCP address information:

  1. type TCPAddr struct {
  2. IP IP
  3. Port int
  4. }

We use the ResolveTCPAddr function to get a TCPAddr in Go:

  1. func ResolveTCPAddr(net, addr string) (*TCPAddr, os.Error)
  • Arguments of net can be one of “tcp4”, “tcp6” or “tcp”, which each signify IPv4-only, IPv6-only, and either IPv4 or IPv6, respectively.
  • addr can be a domain name or IP address, like “www.google.com:80” or “127.0.0.1:22”.

TCP client

Go clients use the DialTCP function in the net package to create a TCP connection, which returns a TCPConn object; after a connection is established, the server has the same type of connection object for the current connection, and client and server can begin exchanging data with one another. In general, clients send requests to servers through a TCPConn and receive information from the server response; servers read and parse client requests, then return feedback. This connection will remain valid until either the client or server closes it. The function for creating a connection is as follows:

  1. func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error)
  • Arguments of net can be one of “tcp4”, “tcp6” or “tcp”, which each signify IPv4-only, IPv6-only, and either IPv4 or IPv6, respectively.
  • laddr represents the local address, set it to nil in most cases.
  • raddr represents the remote address.

Let’s write a simple example to simulate a client requesting a connection to a server based on an HTTP request. We need a simple HTTP request header:

  1. "HEAD / HTTP/1.0\r\n\r\n"

Server response information format may look like the following:

  1. HTTP/1.0 200 OK
  2. ETag: "-9985996"
  3. Last-Modified: Thu, 25 Mar 2010 17:51:10 GMT
  4. Content-Length: 18074
  5. Connection: close
  6. Date: Sat, 28 Aug 2010 00:43:48 GMT
  7. Server: lighttpd/1.4.23

Client code:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "os"
  7. )
  8. func main() {
  9. if len(os.Args) != 2 {
  10. fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
  11. os.Exit(1)
  12. }
  13. service := os.Args[1]
  14. tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
  15. checkError(err)
  16. conn, err := net.DialTCP("tcp", nil, tcpAddr)
  17. checkError(err)
  18. _, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
  19. checkError(err)
  20. result, err := ioutil.ReadAll(conn)
  21. checkError(err)
  22. fmt.Println(string(result))
  23. os.Exit(0)
  24. }
  25. func checkError(err error) {
  26. if err != nil {
  27. fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
  28. os.Exit(1)
  29. }
  30. }

In the above example, we use user input as the service argument of net.ResolveTCPAddr to get a tcpAddr. Passing tcpAddr to the DialTCP function, we create a TCP connection, conn. We can then use conn to send request information to the server. Finally, we use ioutil.ReadAll to read all the content from conn, which contains the server response.

TCP server

We have a TCP client now. We can also use the net package to write a TCP server. On the server side, we need to bind our service to a specific inactive port and listen for any incoming client requests.

  1. func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error)
  2. func (l *TCPListener) Accept() (c Conn, err os.Error)

The arguments required here are identical to those required by the DialTCP function we used earlier. Let’s implement a time syncing service using port 7777:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "time"
  7. )
  8. func main() {
  9. service := ":7777"
  10. tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
  11. checkError(err)
  12. listener, err := net.ListenTCP("tcp", tcpAddr)
  13. checkError(err)
  14. for {
  15. conn, err := listener.Accept()
  16. if err != nil {
  17. continue
  18. }
  19. daytime := time.Now().String()
  20. conn.Write([]byte(daytime)) // don't care about return value
  21. conn.Close() // we're finished with this client
  22. }
  23. }
  24. func checkError(err error) {
  25. if err != nil {
  26. fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
  27. os.Exit(1)
  28. }
  29. }

After the service is started, it waits for client requests. When it receives a client request, it Accepts it and returns a response to the client containing information about the current time. It’s worth noting that when errors occur in the for loop, the service continues running instead of exiting. Instead of crashing, the server will record the error to a server error log.

The above code is still not good enough, however. We didn’t make use of goroutines, which would have allowed us to accept simultaneous requests. Let’s do this now:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "time"
  7. )
  8. func main() {
  9. service := ":1200"
  10. tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
  11. checkError(err)
  12. listener, err := net.ListenTCP("tcp", tcpAddr)
  13. checkError(err)
  14. for {
  15. conn, err := listener.Accept()
  16. if err != nil {
  17. continue
  18. }
  19. go handleClient(conn)
  20. }
  21. }
  22. func handleClient(conn net.Conn) {
  23. defer conn.Close()
  24. daytime := time.Now().String()
  25. conn.Write([]byte(daytime)) // don't care about return value
  26. // we're finished with this client
  27. }
  28. func checkError(err error) {
  29. if err != nil {
  30. fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
  31. os.Exit(1)
  32. }
  33. }

By separating out our business process from the handleClient function, and by using the go keyword, we’ve already implemented concurrency in our service. This is a good demonstration of the power and simplicity of goroutines.

Some of you may be thinking the following: this server does not do anything meaningful. What if we needed to send multiple requests for different time formats over a single connection? How would we do that?

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "time"
  7. "strconv"
  8. )
  9. func main() {
  10. service := ":1200"
  11. tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
  12. checkError(err)
  13. listener, err := net.ListenTCP("tcp", tcpAddr)
  14. checkError(err)
  15. for {
  16. conn, err := listener.Accept()
  17. if err != nil {
  18. continue
  19. }
  20. go handleClient(conn)
  21. }
  22. }
  23. func handleClient(conn net.Conn) {
  24. conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
  25. request := make([]byte, 128) // set maximum request length to 128B to prevent flood based attacks
  26. defer conn.Close() // close connection before exit
  27. for {
  28. read_len, err := conn.Read(request)
  29. if err != nil {
  30. fmt.Println(err)
  31. break
  32. }
  33. if read_len == 0 {
  34. break // connection already closed by client
  35. } else if string(request[:read_len]) == "timestamp" {
  36. daytime := strconv.FormatInt(time.Now().Unix(), 10)
  37. conn.Write([]byte(daytime))
  38. } else {
  39. daytime := time.Now().String()
  40. conn.Write([]byte(daytime))
  41. }
  42. }
  43. }
  44. func checkError(err error) {
  45. if err != nil {
  46. fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
  47. os.Exit(1)
  48. }
  49. }

In this example, we use conn.Read() to constantly read client requests. We cannot close the connection because clients may issue more than one request. Due to the timeout we set using conn.SetReadDeadline(), the connection closes automatically after our allotted time period. When the expiry time has elapsed, our program breaks from the for loop. Notice that request needs to be created with a max size limitation in order to prevent flood attacks.

Controlling TCP connections

Controlling TCP functions:

  1. func DialTimeout(net, addr string, timeout time.Duration) (Conn, error)

Setting the timeout of connections. These are suitable for use on both clients and servers:

  1. func (c *TCPConn) SetReadDeadline(t time.Time) error
  2. func (c *TCPConn) SetWriteDeadline(t time.Time) error

Setting the write/read timeout of one connection:

  1. func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error

It’s worth taking some time to think about how long you want your connection timeouts to be. Long connections can reduce the amount of overhead involved in creating connections and are good for applications that need to exchange data frequently.

For more detailed information, just look up the official documentation for Go’s net package .

UDP sockets

The only difference between a UDP socket and a TCP socket is the processing method for dealing with multiple requests on server side. This arises from the fact that UDP does not have a function like Accept. All of the other functions have UDP counterparts; just replace TCP with UDP in the functions mentioned above.

  1. func ResolveUDPAddr(net, addr string) (*UDPAddr, os.Error)
  2. func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error)
  3. func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error)
  4. func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error
  5. func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error)

UDP client code sample:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. )
  7. func main() {
  8. if len(os.Args) != 2 {
  9. fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
  10. os.Exit(1)
  11. }
  12. service := os.Args[1]
  13. udpAddr, err := net.ResolveUDPAddr("udp4", service)
  14. checkError(err)
  15. conn, err := net.DialUDP("udp", nil, udpAddr)
  16. checkError(err)
  17. _, err = conn.Write([]byte("anything"))
  18. checkError(err)
  19. var buf [512]byte
  20. n, err := conn.Read(buf[0:])
  21. checkError(err)
  22. fmt.Println(string(buf[0:n]))
  23. os.Exit(0)
  24. }
  25. func checkError(err error) {
  26. if err != nil {
  27. fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
  28. os.Exit(1)
  29. }
  30. }

UDP server code sample:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "time"
  7. )
  8. func main() {
  9. service := ":1200"
  10. udpAddr, err := net.ResolveUDPAddr("udp4", service)
  11. checkError(err)
  12. conn, err := net.ListenUDP("udp", udpAddr)
  13. checkError(err)
  14. for {
  15. handleClient(conn)
  16. }
  17. }
  18. func handleClient(conn *net.UDPConn) {
  19. var buf [512]byte
  20. _, addr, err := conn.ReadFromUDP(buf[0:])
  21. if err != nil {
  22. return
  23. }
  24. daytime := time.Now().String()
  25. conn.WriteToUDP([]byte(daytime), addr)
  26. }
  27. func checkError(err error) {
  28. if err != nil {
  29. fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
  30. os.Exit(1)
  31. }
  32. }

Summary

Through describing and coding some simple programs using TCP and UDP sockets, we can see that Go provides excellent support for socket programming, and that they are fun and easy to use. Go also provides many functions for building high performance socket applications.