Golang network communication

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

Title:golang Network Programming

Golang Network Programming

Go-shadowsocks is a very good example of learning Golang network programming. In this blog post, the key
This paper expounds the implementation of service-side and client in several different protocols of Golang network communication.
The network communication protocol has the following two types plus an additional protocol

    • Golang TCP
    • Golang upd
    • Golang KCP: An enhanced protocol on the UPD, KCP is a fast and reliable protocol that can cost 10% to 20% less than TCP, in exchange for an average delay of 30% to 40%, and a maximum delay of three times times the transmission effect.

One of the great advantages of Golang is multicore, parallel, and network programming. By Goroutine and channel can be very convenient to co-process, turndown threads more lightweight, occupy less resources, can be better suited to parallel computing.

These three types are described below.

Golang TCP

The following is illustrated by two examples of Golang TCP server and client

Single-Connection TCP server and client side

TCP Server

package mainimport (    "net"    "fmt")func main(){    // tcp 监听并接受端口    l, err := net.Listen("tcp", "127.0.0.1:65535")    if err != nil {        fmt.Println(err)        return    }    //最后关闭    defer l.Close()    fmt.Println("tcp服务端开始监听65535端口...")    // 使用循环一直接受连接    for {        fmt.Println("loop test")        //Listener.Accept() 接受连接        //conn 是双方的。和长度为1的channel有些类似。        c, err := l.Accept()        if err!= nil {            return        }        //处理tcp请求        go handleConnection(c)    }}func handleConnection(c net.Conn) {    //一些代码逻辑...    fmt.Println("tcp服务端开始处理请求...")    //读取    buffer := make([]byte, 1024)    //如果客户端无数据则会阻塞,服务端阻塞,直到等待客户端传递数据。    c.Read(buffer)    //服务端成功从阻塞状态走出,读取客户端的数据,并根据自身的接口输出buffer    c.Write(buffer)    fmt.Println("tcp服务端开始处理请求完毕...")}

TCP Client

package mainimport (    "net"    "fmt")func main()  {    //net.dial 拨号 获取tcp连接    conn, err := net.Dial("tcp", "127.0.0.1:65535")    if err != nil {        fmt.Println(err)        return    }    fmt.Println("获取127.0.0.1:65535的tcp连接成功...")    defer conn.Close()    //客户端这里不用使用协程。使用协程的话main函数退出,所有go 协程全部死掉。    conn.Write([]byte("echo data to server ,then to client!!!"))    fmt.Println("test server")    //读取到buffer    buffer := make([]byte, 1024)    //如果服务端没有把数据传递过来,那么客户端阻塞,直到服务端向其中写入了数据。    conn.Read(buffer)    fmt.Println(string(buffer))}

NET Utils

    • Net. Dial (client call, dialing)
    • Net. Listen (server-side call, listener interface)
    • Tcplistener.accept (server-side invoke, accept, create connection.) )
    • Conn. Read (called by the client service side to read the data in conn)
    • Conn.write (called by client server, reads data from conn)

Other Net-provided functions can view the API

To enable the server to process multiple connections, a coprocessor is used to process connection requests from multiple clients.

The implementation of the client is not used by the co-process.

In addition to the TCP server for function is very interesting, in the above test example does not print indefinitely loop test , indicating that there is blocking. Only when a new connection comes will it let go.

Dual connection TCP server and client side

In the example above, there are the following problems:

    • There is only one connection between server and client. This can happen: the server needs to push some data to the client. The connection established by the client is in block state.
    • The connection that the server establishes with the client is a short connection.

There are the following workarounds

    • Add the server module to the client implementation, listen for requests from the server, and process them.
    • In addition, a long connection is established between the server and the client. To live by Setkeeplive.
    • Use the channel to ensure that the client's co-operation is not lost.

Golang UDP

UDP communication does not require the creation of Lister, which transmits data directly.

UDP server

package mainimport (    "fmt"    "net")func main() {    // 创建监听    socket, err := net.ListenUDP("udp4", &net.UDPAddr{        IP:   net.IPv4(127,0,0,1),        Port: 23452,    })    if err != nil {        fmt.Println("监听失败!", err)        return    }    fmt.Println("监听成功")    defer socket.Close()    for {        // 读取数据        data := make([]byte, 4096)        read, remoteAddr, err := socket.ReadFromUDP(data)        if err != nil {            fmt.Println("读取数据失败!", err)            continue        }        fmt.Println(read, remoteAddr)        fmt.Printf("%s\n\n", data)        // 发送数据        senddata := []byte("hello client!")        _, err = socket.WriteToUDP(senddata, remoteAddr)        if err != nil {            return            fmt.Println("发送数据失败!", err)        }    }}

UDP client

package mainimport (    "fmt"    "net")func main() {    // 创建连接    socket, err := net.DialUDP("udp4", nil, &net.UDPAddr{        IP:   net.IPv4(127,0,0,1),        Port: 23452,    })    if err != nil {        fmt.Println("连接失败!", err)        return    }    defer socket.Close()    // 发送数据    senddata := []byte("hello server!")    _, err = socket.Write(senddata)    if err != nil {        fmt.Println("发送数据失败!", err)        return    }    // 接收数据    data := make([]byte, 4096)    read, remoteAddr, err := socket.ReadFromUDP(data)    if err != nil {        fmt.Println("读取数据失败!", err)        return    }    fmt.Println(read, remoteAddr)    fmt.Printf("%s\n", data)}

The above server and client implementations are relatively straightforward, and there's basically nothing to say.

Golang KCP

Reference links

    • Http://www.jb51.net/article/89075.htm
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.