The gudp module provides a very simple and easy-to-use gudp.Conn link operation object.

Usage:

  1. import "github.com/gogf/gf/v2/net/gudp"

API Documentation: https://pkg.go.dev/github.com/gogf/gf/v2/net/gudp

Introduction

Most of the operations of gudp.Conn are similar to the operation mode of gtcp (most of the method names are the same), but since UDP is a connectionless protocol, gudp.Conn (underlying communication port) can only complete up to one data write and read at a time. The client will need to create a new Conn object for communication the next time it communicates with the target server.

Usage Example

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/net/gudp"
  8. "github.com/gogf/gf/v2/os/gtime"
  9. )
  10. func main() {
  11. var (
  12. ctx = context.Background()
  13. logger = g.Log()
  14. )
  15. // Server
  16. go gudp.NewServer("127.0.0.1:8999", func(conn *gudp.ServerConn) {
  17. defer conn.Close()
  18. for {
  19. data, addr, err := conn.Recv(-1)
  20. if len(data) > 0 {
  21. if err = conn.Send(append([]byte("> "), data...), addr); err != nil {
  22. logger.Error(ctx, err)
  23. }
  24. }
  25. if err != nil {
  26. logger.Error(ctx, err)
  27. }
  28. }
  29. }).Run()
  30. time.Sleep(time.Second)
  31. // Client
  32. for {
  33. if conn, err := gudp.NewClientConn("127.0.0.1:8999"); err == nil {
  34. if b, err := conn.SendRecv([]byte(gtime.Datetime()), -1); err == nil {
  35. fmt.Println(string(b), conn.LocalAddr(), conn.RemoteAddr())
  36. } else {
  37. logger.Error(ctx, err)
  38. }
  39. conn.Close()
  40. } else {
  41. logger.Error(ctx, err)
  42. }
  43. time.Sleep(time.Second)
  44. }
  45. }

This example is similar to the communication example in gtcp.Conn, with the difference that the client and server cannot maintain a connection, requiring a new connection object for each communication.

After execution, the output is as follows:

  1. > 2018-07-21 23:13:31 127.0.0.1:33271 127.0.0.1:8999
  2. > 2018-07-21 23:13:32 127.0.0.1:45826 127.0.0.1:8999
  3. > 2018-07-21 23:13:33 127.0.0.1:58027 127.0.0.1:8999
  4. > 2018-07-21 23:13:34 127.0.0.1:33056 127.0.0.1:8999
  5. > 2018-07-21 23:13:35 127.0.0.1:39260 127.0.0.1:8999
  6. > 2018-07-21 23:13:36 127.0.0.1:33967 127.0.0.1:8999
  7. > 2018-07-21 23:13:37 127.0.0.1:52359 127.0.0.1:8999
  8. ...