In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the knowledge points of Go language network programming". In the daily operation, I believe that many people have doubts about the knowledge points of Go language network programming. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the questions of "what are the knowledge points of Go language network programming?" Next, please follow the editor to study!
1. Socket programming
When we write network programs in Go language, we will not see the traditional coding form. In the past, when we used to program with Socket, we would follow these steps.
Set up Socket: use the socket () function.
Bind Socket: use the bind () function.
Listening: use the listen () function. Or connect: use the connect () function.
Accept connections: use the accept () function.
Receive: use the receive () function. Or send: use the send () function.
The Go language standard library abstracts and encapsulates this process. No matter what kind of connection we expect to use, all we need to do is call net.Dial ().
1.1 Dial () function
The prototype of the Dial () function is as follows:
Func Dial (net, addr string) (Conn, error)
Where the net parameter is the name of the network protocol, the addr parameter is the IP address or domain name, and the port number is followed by the address or domain name in the form of:. The port number is optional. If the connection is successful, return the connection object, otherwise return error.
Let's take a look at several common ways to invoke protocols.
TCP link:
Conn, err: = net.Dial ("tcp", "192.168.1.8 virtual 3000")
UDP link:
Conn, err: = net.Dial ("udp", "192.168.1.12 purl 975")
ICMP link (using protocol name):
Conn, err: = net.Dial ("ip4:icmp", "www.baidu.com")
ICMP link (using agreement number):
Conn, err: = net.Dial ("ip4:1", "10.0.0.3")
After the connection is successfully established, we can send and receive data. When sending data, use the Write () member method of conn, and use the Read () method when receiving data.
2. HTTP programming 2.1 HTTP client
Go's built-in net/http package provides the simplest HTTP client implementation, and we can request data directly using the most frequently used GET and POST methods in HTTP without the need for third-party network communication libraries such as libcurl.
Basic method
The Client type of the net/http package provides the following methods that allow us to implement the HTTP request in the most concise way:
Func (c * Client) Get (url string) (r * Response, err error) func (c * Client) Post (url string, bodyType string, body io.Reader) (r * Response, err error) func (c * Client) PostForm (url string, data url.Values) (r * Response, err error) func (c * Client) Head (url string) (r * Response, err error) func (c * Client) Do (req * Request) (resp * Response, err error)
The following is an overview of these methods.
Http.Get ()
To request a resource, simply call the http.Get () method (equivalent to http.DefaultClient.Get ()). The sample code is as follows:
Resp, err: = http.Get ("http://example.com/")if err! = nil {/ / handle error. Return} defer resp.Body.close () io.Copy (os.Stdout, resp.Body)
The above code requests the home page of a website and prints its contents to the standard output stream.
Http.Post ()
To send data as POST is also simple, simply call the http.Post () method and pass the following three parameters in turn:
The requested target URL will be the resource type (MIMEType) data bitstream of the POST data (in the form of [] byte)
The following sample code shows how to upload a picture:
Resp, err: = http.Post ("http://example.com/upload"," image/jpeg ", & imageDataBuf) if err! = nil {/ / handling error return} if resp.StatusCode! = http.StatusOK {/ / handling error return}
Http.PostForm ()
The http.PostForm () method implements a form submission with a standard encoding format of application/x-www-form-urlencoded. The following sample code simulates the HTML form to submit a new article:
Resp, err: = http.PostForm ("http://example.com/posts", url.Values {" title ": {" article title "}," content ": {" article body "}}) if err! = nil {/ / handling error return}
Http.Head ()
The Head request method in HTTP indicates that only the header information of the target URL, namely HTTP Header, is requested and no HTTP is returned.
Body . Go's built-in net/http package also provides the http.Head () method, which is the same as the http.Get () method
You only need to pass in one parameter of the target URL. The following sample code requests HTTP Header information for the home page of a website:
Resp, err: = http.Head ("http://baidu.com/")
(* http.Client) .Do ()
In most cases, http.Get () and http.PostForm () can meet the demand, but if we initiate
The HTTP request requires more customized information. We want to set some custom Http Header fields, such as:
Set custom "User-Agent"
Transfer Cookie
At this point, you can use the Do () method of the net/http package http.Client object to implement
Req, err: = http.NewRequest ("GET", "http://baidu.com", nil) / /... req.Header.Add (" User-Agent "," Gobook Custom User-Agent ") / /... client: = & http.Client {/ /...} resp, err: = client.Do (req) 2.2 HTTP server 2.2.1 handles HTTP request
Using the http.ListenAndServe () method provided by the net/http package, you can listen at the specified address and open a HTTP. The prototype of this method on the server is as follows:
Func ListenAndServe (addr string, handler Handler) error
This method is used to listen at the specified TCP network address addr and then call the server handler to process the incoming connection request. This method has two parameters: the first parameter addr is the listening address; the second parameter represents the server handler, which is usually empty, which means that the server calls http.DefaultServeMux for processing, while the business logic handler http.Handle () or http.HandleFunc () written by the server is injected into http.DefaultServeMux by default. The specific code is as follows:
Http.Handle ("/ foo", fooHandler) http.HandleFunc ("/ bar", func (w http.ResponseWriter, r * http.Request) {fmt.Fprintf (w, "Hello,% Q", html.EscapeString (r.URL.Path))}) log.Fatal (http.ListenAndServe (": 8080", nil))
The net/http package also provides a http.ListenAndServeTLS () method to handle HTTPS connection requests:
Func ListenAndServeTLS (addr string, certFile string, keyFile string, handler Handler) error
ListenAndServeTLS () and ListenAndServe () behave the same way, except that only HTTPS requests are processed. In addition, there must be relevant files on the server that contain the certificate and the matching private key, such as certFile corresponding to the SSL certificate file storage path and keyFile corresponding to the certificate private key file path. If the certificate is signed by a certification authority, the path specified by the certFile parameter must be an CA-certified SSL certificate stored on the server.
3. RPC programming
In Go, the net/rpc package provided by the standard library implements the relevant details of the RPC protocol, and developers can easily use this package to write RPC server and client programs, which makes the communication between multiple processes developed in Go language very simple.
The net/rpc package allows RPC client programs to call the exposed methods of a remote object (which must start with an uppercase letter and can be called externally) over a network or other Imax O connection. On the RPC server side, an object can be registered as an accessible service, and then the object's exposed methods can provide access remotely. A RPC server can register multiple objects of different types, but it is not allowed to register multiple objects of the same type.
Only methods in an object that meet the following conditions can be made remotely accessible by the RPC server:
Must be a method that can be called publicly outside the object (the initials are capitalized)
There must be two parameters, and the type of the parameter must be accessible outside the package or supported by Go built-in.
The second parameter must be a pointer
The method must return a value of type error.
The above four conditions can be simply expressed in the following line of code:
Func (t * T) MethodName (argType T1, replyType * T2) error
In the above line of code, types T, T1, and T2 are encoded and decoded by default using Go's built-in encoding/gob packet.
The first parameter of the method (MethodName) represents the parameter passed in by the RPC client, the second parameter represents the result to be returned to the RPC client, and the method finally returns a value of type error.
The RPC server can handle a single connection request by calling rpc.ServeConn. In most cases, it is a good choice to create the service by listening on a network address through TCP or HTTP.
3.1 RPC support and processing in Go language
In Go, the net/rpc package provided by the standard library implements the relevant details of the RPC protocol, and developers can easily use this package to write RPC server and client programs, which makes the communication between multiple processes developed in Go language very simple.
The net/rpc package allows RPC client programs to call the exposed methods of a remote object (which must start with an uppercase letter and can be called externally) over a network or other Imax O connection. On the RPC server side, an object can be registered as an accessible service, and then the object's exposed methods can provide access remotely. A RPC server can register multiple objects of different types, but it is not allowed to register multiple objects of the same type.
Only methods in an object that meet the following conditions can be made remotely accessible by the RPC server:
Must be a method that can be called publicly outside the object (the initials are capitalized)
There must be two parameters, and the type of the parameter must be accessible outside the package or supported by Go built-in.
The second parameter must be a pointer
The method must return a value of type error.
The above four conditions can be simply expressed in the following line of code:
Func (t * T) MethodName (argType T1, replyType * T2) error
In the above line of code, types T, T1, and T2 are encoded and decoded by default using Go's built-in encoding/gob packet. We will cover the contents of the encoding/gob package later.
The first parameter of the method (MethodName) represents the parameter passed in by the RPC client, the second parameter represents the result to be returned to the RPC client, and the method finally returns a value of type error.
The RPC server can handle a single connection request by calling rpc.ServeConn. In most cases, it is a good choice to create the service by listening on a network address through TCP or HTTP.
3.2 introduction to Gob
Gob is a Go coding and decoding tool for serializing data structures, and the encoding/gob package is built into the Go standard library for use. After a data structure is serialized using Gob, it can be used for network transmission.
Different from JSON or XML, which is a data exchange language based on text description, Gob is a binary encoded data stream, and Gob stream is self-interpretable. It not only ensures high efficiency, but also has complete expression ability.
As a dedicated serialization method for encoding and decoding Go's data structures, this means that Gob cannot be used across languages. In the net/rpc packet of Go, the codec used to transmit data is Gob by default. Since Gob is limited to programs developed in the Go language, this means that we can only use Go's RPC to achieve interprocess communication.
However, most of the time, our RPC server (or client) written in Go may prefer it to be generic, language-independent, and can communicate with RPC clients implemented in Python, Java, or other programming languages.
3.3 elegantly designed RPC interface
Go's net/rpc is very flexible, it implements the interface definition of codec before and after data transmission. This means that developers can customize how the data is transmitted and the interaction between the RPC server and the client.
The codec interfaces provided by RPC are as follows:
Type ClientCodec interface {WriteRequest (* Request, interface {}) error ReadResponseHeader (* Response) error ReadResponseBody (interface {}) error Close () error} type ServerCodec interface {ReadRequestHeader (* Request) error ReadRequestBody (interface {}) error WriteResponse (* Response, interface {}) error Close () error}
The interface ClientCodec defines how the RPC client sends requests and reads responses in a RPC session. The client program writes a request to the RPC connection through the WriteRequest () method and reads the response information from the server through ReadResponseHeader () and ReadResponseBody (). When the entire process is complete, the connection is closed by the Close () method.
The interface ServerCodec defines how the RPC server receives a request and sends a response in a RPC session. The server program reads the request information from an RPC connection through the ReadRequestHeader () and ReadRequestBody () methods, and then sends a response to the RPC client in the connection through the WriteResponse () method. When the process is complete, the connection is closed by the Close () method.
By implementing the above interface, we can customize the encoding and decoding method before and after data transmission, not just limited to Gob. Similarly, you can customize the interaction behavior between the RPC server and the client. In fact, the net/rpc/json package provided by the Go standard library is a set of JSON-RPC modules that implement the rpc.ClientCodec and rpc.ServerCodec interfaces.
At this point, the study of "what are the knowledge points of Go language network programming" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.