Home  >  Article  >  Backend Development  >  How to program using UDP in Go?

How to program using UDP in Go?

王林
王林Original
2023-05-11 17:07:361921browse

UDP (User Datagram Protocol) is a connectionless-oriented protocol, which is a very important protocol in the transport layer. It can transmit data directly to the target host without establishing a connection, so it is widely used in real-time data transmission, games and other applications, and is more suitable than TCP in some scenarios.

In Go language, using UDP programming is also very simple. This article will introduce how to use UDP programming in Go language.

  1. Understand the datagram of UDP protocol

In the UDP protocol, data is encapsulated into a UDP packet, also called a datagram. The datagram contains source port number, destination port number, length, checksum and other information.

In the Go language, the UDPConn of the net package can be used to read and write UDP datagrams.

  1. Write UDP server program

In the UDP server program, you first need to create a UDP address, that is, use the ResolveUDPAddr method in the net package. This method receives two parameters, respectively protocol type and server address.

Then, use the ListenUDP method in the net package to listen to the address. This method will return a UDPConn object, which can be used to receive and send UDP datagrams.

The next step is the process of reading the datagram. Use the ReadFromUDP method of the UDPConn object to read the datagram sent by the client. This method will block until the datagram is received and return an error object and datagram object. . After reading the data, you can take out the data and process the data, such as calculating the hash value of the data. Then use the WriteToUDP method of the UDPConn object to send a response datagram to the client.

The following is a simple UDP server program:

package main

import (
    "fmt"
    "net"
)

func main() {
    ip := net.ParseIP("127.0.0.1")
    addr := &net.UDPAddr{
        IP:   ip,
        Port: 8080,
    }

    conn, err := net.ListenUDP("udp", addr)
    if err != nil {
        fmt.Println(err)
        return
    }

    defer conn.Close()
    fmt.Println("UDP server listening on port ", addr.Port)
    for {
        data := make([]byte, 1024)
        n, addr, err := conn.ReadFromUDP(data)
        if err != nil {
            fmt.Println("Error: ", err)
            continue
        }
        fmt.Printf("Received from %s:%d : %s
", addr.IP.String(), addr.Port, string(data[:n]))

        reply := []byte("Hello from UDP server")
        conn.WriteToUDP(reply, addr)
    }
}
  1. Writing UDP client program

In the UDP client program, you first need to create A UDP address, that is, use the ResolveUDPAddr method in the net package. This method receives two parameters, namely the protocol type and the server address.

Then, use the DialUDP method to connect to the server address. This method will return a UDPConn object, which can be used to send UDP datagrams to the server.

The next step is to send the datagram to the server. Use the Write method of the UDPConn object to send the datagram to the server. This method will block until the datagram is sent.

Then, use the ReadFromUDP method of the UDPConn object to read the response datagram from the server. This method will block until the datagram is received and return an error object and datagram object. After reading the data, you can take out the data.

The following is a simple UDP client program:

package main

import (
    "fmt"
    "net"
)

func main() {
    ip := net.ParseIP("127.0.0.1")
    addr := &net.UDPAddr{
        IP:   ip,
        Port: 8080,
    }

    conn, err := net.DialUDP("udp", nil, addr)
    if err != nil {
        fmt.Println(err)
        return
    }

    defer conn.Close()
    fmt.Printf("UDP client connected to %s:%d
", addr.IP.String(), addr.Port)

    message := []byte("Hello from UDP client")
    _, err = conn.Write(message)
    if err != nil {
        fmt.Println(err)
        return
    }

    buffer := make([]byte, 1024)
    n, _, err := conn.ReadFromUDP(buffer)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Printf("Response from server: %s
", string(buffer[:n]))
}
  1. Summary

In Go language, programming with UDP is very simple, just use The UDPConn object in the net package can read and write UDP datagrams. This article introduces how to write UDP server programs and UDP client programs, and provides corresponding code examples. When you need to carry out real-time data transmission, games and other applications, you can consider using the UDP protocol.

The above is the detailed content of How to program using UDP in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn