// Create a UDPConn on a specific port conn, err := net.ListenUDP("udp", &net.UDPAddr{ IP: net.ParseIP("0.0.0.0"), Port: 8080, Zone: "", }) if err != nil { log.Fatal(err) } // Set a read deadline of 10 seconds from now err = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) if err != nil { log.Fatal(err) } // Read from the connection with the read deadline buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { log.Fatal(err) } // Print out the received message fmt.Println(string(buffer[:n]))
// Create a UDPConn on a specific port conn, err := net.ListenUDP("udp", &net.UDPAddr{ IP: net.ParseIP("0.0.0.0"), Port: 8080, Zone: "", }) if err != nil { log.Fatal(err) } // Set a read deadline of 1 second from now err = conn.SetReadDeadline(time.Now().Add(1 * time.Second)) if err != nil { log.Fatal(err) } // Attempt to read from the connection with the read deadline buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { // Check if the error is a timeout error if e, ok := err.(net.Error); !ok || !e.Timeout() { // If it's not a timeout, log the error as usual log.Fatal(err) } // If it is a timeout, handle it gracefully fmt.Println("No data received within timeout") }This example is similar to the previous one, but with a shorter read deadline of 1 second. It attempts to read from the connection within the deadline, but if the operation times out, it handles the error gracefully by printing out a message. Both examples use the net package in Go.