Go - Creating a UDP Client

发布时间 2023-10-16 19:52:18作者: ZhangZhihuiAAA

Problem: You want to create a UDP client to send data to a UDP server.


Solution: Use the Dial function in the net package to connect to a UDP server. Then use the Write method of the net.UDPConn interface to write data to the connection.

 

Creating a UDP client can be very straightforward, and it can look exactly like the TCP client, except the network string is udp instead of tcp :

func   main ()   { 
      conn ,   err   :=   net . Dial ( "udp" ,   ":9001" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 
      conn . Write ([] byte ( "Hello  from  UDP  client" )) 
}

Try it out: set up a UDP listener using nc on one terminal. Use the - u flag to force nc to use UDP and the - l flag to listen for incoming connections:

$  nc  - l  - u  9001

Then run your UDP client on another terminal. You should see “Hello from UDP client” printed out on the server side. 

This works for IPv4 and IPv6. To test this, you’ll use the - 6 flag to force nc to use IPv6 on the server side:

$  nc  - l  - u  - 6  9001

If you run the same client you should see the same output. 

You can also use the net.DialUDP function to create a UDP client:

func   main ()   { 
      raddr ,   err   :=   net . ResolveUDPAddr ( "udp" ,   ":9001" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      conn ,   err   :=   net . DialUDP ( "udp" ,   nil ,   raddr ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 

      _ ,   err   =   conn . Write ([] byte ( "Hello  from  UDP  client" )) 

      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
}

The net.DialUDP function takes a net.UDPAddr as argument. First, use the ne⁠t.R⁠es⁠ol⁠veUD⁠PA⁠dd⁠r function to resolve and create the address. Then use the net.DialUDP function to create the connection. 

To write to the connection use the Write method of the net.UDPConn interface. The Write method takes a byte slice as an argument and returns the number of bytes written and an error.