Socket programming for Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

many types, functions, and methods are defined in the Go NET package for network programming, where the definition of IP is as follows:

Type IP []byte
The IP address you enter needs to be parsed to avoid entering an IP address in the wrong format:
Func Parseip (s string) IP
The argument s can be a IPv4 or IPv6 address of the string type, and nil will be returned if parsing the error.

There is a type tcpconn in the Go Language net package, which can be used as a channel for client and server-side interaction, and he has two main functions:

Func (c *tcpconn) Write (b []byte) (n int, err OS. Error) func (c *tcpconn) Read (b []byte) (n int, err OS. Error)
Tcpconn can be used to read and write data on the client and server side. The address information for TCP is represented by TCPADDR:
Type tcpaddr struct {    IP ip    Port int}
Get a tcpaddr by resolvetcpaddr:
Func resolvetcpaddr (NET, addr string) (*tcpaddr, OS. Error)
    • NET parameter is either "TCP4", "TCP6", or "TCP", which represents TCP (Ipv4-only), TCP (IPV6-ONLY), or TCP (any one of the Ipv4,ipv6), respectively.
    • Addr represents a domain name or IP address, such as "www.google.com:80" or "127.0.0.1:22".
A TCP connection is established through the DIALTCP function in the net package, and an object of type Tcpconn is returned, and the server side creates an object of the same type when the connection is established, at which point the client and server segments Exchange data through the respective Tcpconn objects. Typically, the client sends the request information to the server side through the Tcpconn object, reading the server-side response. The server reads and resolves the request from the client and returns the reply message, which is not invalidated until either end of the connection is closed, or the connection can be used all the time. The function that establishes the connection is defined as follows:
Func dialtcp (NET string, laddr, Raddr *tcpaddr) (c *tcpconn, err OS. Error)
    • NET parameter is any of the "TCP4", "TCP6", and "TCP", representing either TCP (Ipv4-only), TCP (IPV6-ONLY), or TCP (any one of the Ipv4,ipv6)
    • LADDR represents the native address and is generally set to nil
    • RADDR represents the remote service address
The client code looks like this:
Package Mainimport (    "FMT"    "io/ioutil" "    Net" "    OS") Func main () {    If Len (OS. Args)! = 2 {        FMT. fprintf (OS. Stderr, "Usage:%s host:port", OS. Args[0])        OS. Exit (1)    }    Service: = OS. ARGS[1]    tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", Service)    checkerror (ERR)    conn, err: = Net. DIALTCP ("TCP", Nil, tcpaddr)    checkerror (Err)    _, Err = conn. Write ([]byte ("head/http/1.0\r\n\r\n"))    checkerror (err)    result, err: = Ioutil. ReadAll (conn)    CheckError (err)    FMT. PRINTLN (string result)    OS. Exit (0)}func checkerror (err error) {    If err! = Nil {        FMT. fprintf (OS. Stderr, "Fatal Error:%s", err. Error ())        OS. Exit (1)    }}
On the server side we need to bind the service to the specified non-active port and listen to this port, and when a client request arrives, it can receive a request from the client connection. NET package has functions in the corresponding function, the function is defined as follows:
Func listentcp (NET string, Laddr *tcpaddr) (l *tcplistener, err os. Error) func (L *tcplistener) Accept () (c Conn, err OS. Error)
The server-side code is as follows:
Package Mainimport ("FMT" "NET" "OS" "Time" "StrConv") func main () {service: = ":" Tcpaddr, err : = Net. RESOLVETCPADDR ("TCP4", Service) CheckError (ERR) listener, err: = Net. LISTENTCP ("TCP", TCPADDR) CheckError (err) for {conn, err: = Listener. Accept () if err! = nil {Continue} go handleclient (conn)}}func handleclient (conn net. Conn) {Conn. Setreaddeadline (time. Now (). ADD (2 * time. Minute)//Set 2 minutes Timeout Request: = make ([]byte, +)//Set Maxium request length to 128KB to prevent flood a Ttack defer Conn. Close ()//close connection before exit for {Read_len, err: = conn. Read (Request) if err! = Nil {fmt.        Println (ERR) Break} if Read_len = = 0 {break//connection already closed by client } else if string (request) = = "Timestamp" {daytime: = StrConv. Formatint (time. Now (). Unix (), Conn. Write ([]byte(daytime)) } else {daytime: = time. Now (). String () Conn. Write ([]byte (Daytime)}} request = Make ([]byte, +)//clear last Read content}}func checkerror (Err er ROR) {if err! = Nil {fmt. fprintf (OS. Stderr, "Fatal Error:%s", err. Error ()) OS. Exit (1)}}

TCP has a lot of connection control functions, we usually use more than a few of the following functions:

Func dialtimeout (NET, addr string, timeout time. Duration) (Conn, error)

Sets the time-out period for the connection to be established, both on the client and server side, and when the setup time is exceeded, the connection is automatically closed.

Func (c *tcpconn) Setreaddeadline (t time. Time) Errorfunc (c *tcpconn) Setwritedeadline (t time. Time) Error

Used to set the time-out for writing/reading a connection. When the setting time is exceeded, the connection is automatically closed.

Func (c *tcpconn) setkeepalive (keepalive bool) OS. Error

Setting the client to maintain a long connection with the server can reduce the handshake overhead when establishing a TCP connection, and is useful for scenarios where frequent data exchange is required.

The difference between processing a UDP socket and a TCP socket in the Go Language pack is that the server side handles multiple client request packets differently, and UDP lacks the Accept function for client connection requests. The rest is almost identical, except that TCP is replaced by UDP. Several of the main functions of UDP are as follows:

Func resolveudpaddr (NET, addr string) (*udpaddr, OS. Error) Func dialudp (net string, laddr, Raddr *udpaddr) (c *udpconn, err OS. Error) Func listenudp (net string, Laddr *udpaddr) (c *udpconn, err OS. Error) func (c *udpconn) readfromudp (b []byte) (n int, addr *udpaddr, err os. Errorfunc (c *udpconn) writetoudp (b []byte, addr *udpaddr) (n int, err OS. Error)
The client code for UDP is as follows:
Package Mainimport (    "FMT"    "NET" "    OS") Func main () {    If Len (OS. Args)! = 2 {        FMT. fprintf (OS. Stderr, "Usage:%s host:port", OS. Args[0])        OS. Exit (1)    }    Service: = OS. ARGS[1]    udpaddr, err: = Net. RESOLVEUDPADDR ("UDP4", Service)    checkerror (ERR)    conn, err: = Net. DIALUDP ("UDP", Nil, udpaddr)    checkerror (Err)    _, Err = conn. Write ([]byte ("Anything"))    checkerror (err)    var buf [512]byte    n, err: = conn. Read (buf[0:])    checkerror (err)    FMT. Println (String (buf[0:n))    OS. Exit (0)}func checkerror (err error) {    If err! = Nil {        FMT. fprintf (OS. Stderr, "Fatal error", Err. Error ())        OS. Exit (1)    }}
The server-side code is as follows:
Package Mainimport (    "FMT"    "NET" "    OS" "Time    ") func main () {    Service: = ": Udpaddr"    , err: = Net. RESOLVEUDPADDR ("UDP4", Service)    checkerror (ERR)    conn, err: = Net. LISTENUDP ("UDP", udpaddr)    checkerror (err) for    {        handleclient (conn)    }}func handleclient (Conn *net . Udpconn) {    var buf [512]byte    _, addr, err: = conn. READFROMUDP (buf[0:])    if err! = Nil {        return    }    Daytime: = time. Now (). String ()    Conn. WRITETOUDP ([]byte (Daytime), addr)}func checkerror (err error) {    If err! = Nil {        FMT. fprintf (OS. Stderr, "Fatal error", Err. Error ())        OS. Exit (1)    }}
It is seen that TCP and UDP conn objects are different, the former is net. Conn, the latter is net. Udpconn. In addition, the server side of UDP read and write is to take the address, this address is the client's address.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.