In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "the method of TCP/IP network programming in Go language". In the daily operation, I believe that many people have doubts about the method of TCP/IP network programming in GE language. 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 doubts about "the method of TCP/IP network programming in Go language". Next, please follow the editor to study!
Application scenario of sending data in TCP/IP layer
Of course, in many cases, but not in most cases, it is certainly better to use higher-level network protocols, because you can use gorgeous API, which hides a lot of technical details. Now there are many choices according to different requirements, such as message queuing protocol, gRPC, protobuf, FlatBuffers, RESTful website API, websocket, and so on.
However, in some special scenarios, especially small projects, choosing any other way can feel too bloated, not to mention that you need to introduce additional dependency packages.
Fortunately, using the standard library's net package to create simple network communication is no more difficult than you might have seen.
Because there are two simplifications in the Go language.
Simplification 1: connections are io streams
The net.Conn interface implements io.Reader, io.Writer and io.Closer interfaces. So TCP connections can be treated like any other io stream.
You might think, "well, it's nice that I can send string or byte fragments in TCP, but what about complex data structures? for example, we're dealing with structured data?"
Simplification 2: the Go language knows how to effectively decode complex types
When it comes to sending encoded structured data over the network, the first thing that comes to mind is JSON. But wait a minute-the Go language's standard library, the encoding/gob package, provides a way to serialize and send sequence Go data types without adding string tags to structures, Go-incompatible JSON, or waiting to use json.Unmarshal to painstakingly parse text into binary data.
Gob encoding and decoding can directly manipulate io streams, which perfectly matches the first simplification.
Let's implement a simple App through these two simplified rules together.
The goal of this simple APP
This app should do two things:
Send and receive simple string messages.
Send and receive structures through gob.
The first part, sending a simple string, demonstrates how easy it is to send data over a TCP/IP network without the need for advanced protocols.
The second part, a little deeper, sends complete structures over the network, which use strings, fragments, maps, and even recursive pointers to themselves.
Thanks to the gob package, it's easy to do this.
Client / server
Structure to be sent after decoding
TestStruct structure testStruct structure
| | ^ |
V |
Gob Encoding-> gob Decoding
| | ^ |
V |
Send = network = receive
Basic elements of sending string data through TCP
On the sending end
Sending a string requires three simple steps:
Open the connection corresponding to the receiving process.
Write a string.
Close the connection.
The net package provides a pair of ways to do this.
ResolveTCPAddr (): this function returns the TCP terminal address.
DialTCP (): similar to dialing in TCP networks.
Both methods are defined in the src/net/tcpsock.go file of the go source code.
Func ResolveTCPAddr (network, address string) (* TCPAddr, error) {switch network {case "tcp", "tcp4", "tcp6": case ": / / a hint wildcard for Go 1.0 undocumented behavior network =" tcp "default: return nil, UnknownNetworkError (network)} addrs, err: = DefaultResolver.internetAddrList (context.Background (), network, address) if err! = nil {return nil, err} return addrs.forResolve (network, address). (* TCPAddr), nil}
ResolveTCPAddr () receives two string parameters.
Network: must be a TCP network name, such as tcp, tcp4, tcp6.
Address: TCP address string. If it is not a literal IP address or port number is not a literal port number, ResolveTCPAddr resolves the incoming address to the address of the TCP terminal. Otherwise, pass in a pair of literal IP addresses and port digits as addresses. The address parameter can use the host name, but this is not recommended because it returns at most one IP address of the host name.
The string that ResolveTCPAddr () receives that represents the TCP address (for example, localhost:80, 127.0.0.1 localhost:80 80, or [:: 1]: 80, all represents the native port 80), returns (net.TCPAddr pointer, nil) ((nil, error) if the string cannot be resolved to a valid TCP address).
Func DialTCP (network string, laddr, raddr * TCPAddr) (* TCPConn, error) {switch network {case "tcp", "tcp4", "tcp6": default: return nil, & OpError {Op: "dial", Net: network, Source: laddr.opAddr (), Addr: raddr.opAddr (), Err: UnknownNetworkError (network)} if raddr = = nil {return nil, & OpError {Op: "dial", Net: network, Source: laddr.opAddr (), laddr.opAddr: Addr, Addr: nil} c Err: = dialTCP (context.Background (), network, laddr, raddr) if err! = nil {return nil, & OpError {Op: "dial", Net: network, Source: laddr.opAddr (), Addr: raddr.opAddr (), Err: err}} return c, nil}
The DialTCP () function takes three parameters:
Network: this parameter, like the network parameter of ResolveTCPAddr, must be the TCP network name.
Laddr: a pointer of type TCPAddr that represents the local TCP address.
Raddr: a pointer of type TCPAddr, which represents a remote TCP address.
It connects to dial two TCP addresses and returns the connection as a net.TCPConn object (connection failure returns error). If we don't need too much control over the Dial setting, then we can use Dial () instead.
Func Dial (network, address string) (Conn, error) {var d Dialer return d.Dial (network, address)}
The Dial () function receives an TCP address and returns a normal net.Conn. This is enough for our test cases. However, if you need features available only on TCP connections, you can use TCP variants (DialTCP, TCPConn, TCPAddr, etc.).
After dialing successfully, we can treat the new connection in the same way as other input and output streams as described above. We can even wrap the connection in bufio.ReadWriter so that we can use various ReadWriter methods, such as ReadString (), ReadBytes, WriteString, and so on.
Func Open (addr string) (* bufio.ReadWriter, error) {conn, err: = net.Dial ("tcp", addr) if err! = nil {return nil, errors.Wrap (err, "Dialing" + addr+ "failed")} / / wraps net.Conn objects into bufio.ReadWriter return bufio.NewReadWriter (bufio.NewReader (conn), bufio.NewWriter (conn)), nil}
Remember that the buffer Writer needs to call the Flush () method after writing, so that all the data will be brushed to the underlying network connection.
Finally, each connection object has a Close () method to terminate the communication.
Fine tuning (fine tuning)
The Dialer structure is defined as follows:
Type Dialer struct {Timeout time.Duration Deadline time.Time LocalAddr Addr DualStack bool FallbackDelay time.Duration KeepAlive time.Duration Resolver * Resolver Cancel
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.