GO Network Programming Language

socket programming

Socket is BSD UNIX process communication mechanism, commonly referred to as "socket" is used to describe IP address and port, the handle is a communication chain. Socket can be understood as API TCP / IP network, it defines a number of functions or routines that programmers can use to develop applications on a TCP / IP network. Applications running on the computer typically sends a request to the network through a "socket" network request or response.
Socket software application is an intermediate layer and a TCP / IP protocol suite to communicate abstraction layer. In design mode, Socket is actually a facade pattern, it is the complexity of TCP / IP protocol suite is hidden behind the Socket, users only need to call the relevant function Socket provisions, let go Socket organization meets the specified protocol data is then communication.

GO language TCP communication

TCP protocol

TCP / IP (Transmission Control Protocol / Internet Protocol) Transmission Control Protocol / Internet Protocol, is a connection (connection-oriented) oriented, reliable byte stream transport layer (Transport layer) based communication protocol, as is the connection-oriented protocols, the same transmission data as the water, there will be problems sticky package.

TCP server

A TCP server can connect many clients, creating multiple goroutine concurrency it is very convenient and efficient Go languages, it is possible to establish a link to each create a goroutine to deal with.
TCP server program process flow:

  • Listening port
  • Receiving client requests to establish links
  • Goroutine handle links created
    TCP server:
//TCP server端

func process(conn net.Conn)  {
    defer conn.Close()  //关闭连接
    for {
        reader := bufio.NewReader(conn)
        var buf [128]byte
        n,err := reader.Read(buf[:])    //读取数据
        if err != nil{
            fmt.Println("连接客户端失败,错误信息:",err)
        }
        recvStr := string(buf[:n])
        fmt.Println("收到客户端信息:",recvStr)
        conn.Write([]byte(recvStr)) //发送数据
    }
}
func main()  {
    listen,err := net.Listen("tcp","127.0.0.1:8888")
    if err != nil{
        fmt.Println("监听失败,错误:",err)
        return
    }
    for {
        conn,err := listen.Accept() //建立连接
        if err!= nil{
            fmt.Println("建立连接失败,错误:",err)
            continue
        }
        go process(conn)    //启动一个goroutine处理连接
    }
}

TCP Client

A TCP client TCP communication process is as follows:

  • The link has been established with the server
  • Transmitting and receiving data
  • Close links

TCP client:

//客户端

func main()  {
    conn ,err := net.Dial("tcp","127.0.0.1:8888")
    if err != nil {
        fmt.Println("连接失败,错误:",err)
        return
    }
    defer conn.Close()
    inputReader := bufio.NewReader(os.Stdout)
    for {
        input, _ := inputReader.ReadString('\n')    //读取用户输入
        inputInfo := strings.Trim(input,"\r\n")
        if strings.ToUpper(inputInfo) == "q"{
            return  //如果输入q就退出
        }
        _,err = conn.Write([]byte(inputInfo))   //发送数据
        if err != nil{
            return 
        }
        buf := [512]byte{}
        n,err := conn.Read(buf[:])
        if err != nil{
            fmt.Println("接受失败,错误:",err)
            return 
        }
        fmt.Println(string(buf[:n]))
    }
}

First start the server, after starting client:

$go run main.go
我是客户端
我是客户端
$go run main.go
收到客户端信息: 我是客户端

GO language UDP communication

UDp agreement

UDP protocol (User Datagram Protocol) is the Chinese name of the User Datagram Protocol, is the OSI (Open System Interconnection, Open Systems Interconnection) reference model is a non-transport layer protocol connection, without establishing a connection and data can be transmitted directly reception, are unreliable, no communication timing, but the real-time UDP protocol is better, generally used for live video related fields.

UDP server

//服务端
func main()  {
    listen,err := net.ListenUDP("udp",&net.UDPAddr{
        IP:net.IPv4(0,0,0,0),
        Port:8888,
    })
    if err != nil{
        fmt.Println("监听失败,错误:",err)
        return
    }
    defer listen.Close()
    for {
        var data [1024]byte
        n,addr,err := listen.ReadFromUDP(data[:])
        if err != nil{
            fmt.Println("接收udp数据失败,错误:",err)
            continue
        }
        fmt.Printf("data:%v addr:%v count:%v\n", string(data[:n]), addr, n)
        _ ,err = listen.WriteToUDP(data[:n],addr)   //发送数据
        if err != nil{
            fmt.Println("发送数据失败,错误:",err)
            continue
        }
    }
}

UDP client

//客户端
func main()  {
    socket,err := net.DialUDP("udp",nil,&net.UDPAddr{
        IP:net.IPv4(0,0,0,0),
        Port:8888,
    })
    if err != nil{
        fmt.Println("连接服务器失败,错误:",err)
        return
    }
    defer socket.Close()
    sendData := []byte("hello world!")
    _,err = socket.Write(sendData)
    if err != nil{
        fmt.Println("发送数据失败,错误:",err)
        return
    }
    data := make([]byte,4096)
    n,remoteAddr,err := socket.ReadFromUDP(data)
    if err != nil{
        fmt.Println("接受数据失败,错误:",err)
        return
    }
    fmt.Printf("recv:%v addr:%v count:%v\n", string(data[:n]), remoteAddr, n)
}

First start the server, after starting client:

$go run main.go
recv:hello world! addr:127.0.0.1:8888 count:12
$go run main.go
data:hello world! addr:127.0.0.1:51222 count:12

HTTP client and server

HTTP protocol

Hypertext Transfer Protocol (HTTP, HyperText Transfer Protocol) is the Internet's most widely used method of transmission protocols, all WWW documents must comply with this standard. HTTP was originally designed purpose is to provide a method to publish and receive HTML pages.

HTTP server

net / http packet is further encapsulated packet to the net, and data dedicated to handling the HTTP protocol.

// http server
func sayHi(w http.ResponseWriter,r *http.Request)  {
    fmt.Fprintln(w,"你好,ares!")
}
func main()  {
    http.HandleFunc("/",sayHi)
    err := http.ListenAndServe(":8888",nil)
    if err != nil{
        fmt.Println("Http 服务建立失败,err:",err)
        return
    }
}

HTTP client

func main() {
    resp, err := http.Get("https://www.baidu.com/")
    if err != nil {
        fmt.Println("get failed, err:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("%T\n",body)
    fmt.Println(string(body))
}

After performing at the terminal will be able to output www.baidu.com Home content.

Guess you like

Origin www.cnblogs.com/aresxin/p/GO-yu-yan-wang-luo-bian-cheng.html