1. Overview#
Network programming is actually a vast field, and this article simply demonstrates how to use Golang's network package for communication.
There are two types of network programming:
- TCP socket programming (the mainstream of network programming, based on TCP/IP at the lower level)
- B/S structure HTTP programming (when accessing websites using a browser, the HTTP protocol is used, and HTTP is also implemented using TCP sockets at the lower level)
TCP socket programming:
- Server processing flow:
- Listen on a port
- Accept TCP requests from clients and establish a connection with the client
- Create a goroutine to handle the requests for that connection
- Client processing flow:
- Establish a connection with the server
- Send request data and receive the results returned by the server
- Close the connection
2. Internet Layered Model#
The logical implementation of the Internet is divided into several layers, each responsible for its own content, much like a building where each layer requires support from the layer below. Most of what we encounter is the topmost layer, which is encapsulated layer by layer and presented to us in the most user-friendly way.
3. Several Core Network Packages#
3.1 net#
The net.Dial() method is used for the client to connect to the network.
The net.Listen() method is used for the server to accept network connections.
3.2 net/http#
The net/http package provides functions for developing powerful web servers and clients.
The http.Get() and https.Get() methods can be used by the client to send HTTP and HTTPS requests.
The http.ListenAndServe() method can be used to create a web server, specifying the IP address and TCP port number that the server listens on, and then handle incoming requests in that method.
3.3 http.RoundTripper#
RoundTripper can be seen as middleware for http.Client.
Use cases:
- Caching HTTP responses (if cache exists, retrieve directly from the cache)
- Setting appropriate HTTP headers
- Rate limiting
4. Go Implementation of DNS Query#
The role of DNS (Domain Name System) is to convert IP addresses to domain names or to convert domain names to IP addresses.
5. Go Implementation of Web Functionality#
You can use Go's standard library functions to implement a web server.
If you need a truly powerful web server, it is still recommended to use web servers like Apache or Nginx.
5.1 Web Server#
5.2 Web Client#
6. Go Implementation of TCP Functionality#
6.1 TCP Server#
6.2 TCP Client#
7. Go Implementation of UDP Functionality#
7.1 UDP Server#
7.2 UDP Client#
8. Summary#
This article mainly introduces the Go version of web servers, clients, TCP servers, clients, and UDP servers, clients, as well as the concept of network layering, Go version DNS queries, and several network packages.