UDP connections

UDP is another protocol that is widely used on the internet. It focuses on low latency, which is why it is not as reliable as TCP. It has many applications, from online gaming, to media streaming, and Voice over Internet Protocol (VoIP). In UDP, if a packet is not received, it is lost and will not be sent back again as it would be in TCP. Imagine a VoIP call, where if there's a connection problem you will lose part of the conversation, but when you resume, you keep communicating almost in real time. Using TCP for this kind of application could result in latency accumulating for every packet loss—making the conversation impossible.

In the following example, we'll create a client and a server application. The server will be some sort of echo, sending back the message received from the client, but it will also reverse the message content.

The client will be pretty similar to the TCP one, with some exceptions—it will use the net.ResolveUDPAddr function to get the address and it will use net.DialUDP to get the connection:

func main() {
if len(os.Args) != 2 {
log.Fatalln("Please specify an address.")
}
addr, err := net.ResolveUDPAddr("udp", os.Args[1])
if err != nil {
log.Fatalln("Invalid address:", os.Args[1], err)
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
log.Fatalln("-> Connection:", err)
}
log.Println("-> Connection to", addr)
r := bufio.NewReader(os.Stdin)
b := make([]byte, 1024)
for {
fmt.Print("# ")
msg, err := r.ReadBytes(' ')
if err != nil {
log.Println("-> Message error:", err)
}
if _, err := conn.Write(msg); err != nil {
log.Println("-> Connection:", err)
return
}
n, err := conn.Read(b)
if err != nil {
log.Println("<- Receive error:", err)
}
msg = bytes.TrimSpace(b[:n])
log.Printf("<- %q", msg)
}
}

The server will be pretty different from the TCP one. The main difference is that with TCP, we have a listener that accepts different connections, which are handled separately; meanwhile, the UDP listener is a connection. It can receive data blindly or use the ReceiveFrom method that will also return the recipient's address. This can be used in the WriteTo method to answer, as shown in the following code:

func main() {
if len(os.Args) != 2 {
log.Fatalln("Please specify an address.")
}
addr, err := net.ResolveUDPAddr("udp", os.Args[1])
if err != nil {
log.Fatalln("Invalid address:", os.Args[1], err)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Fatalln("Listener:", os.Args[1], err)
}

b := make([]byte, 1024)
for {
n, addr, err := conn.ReadFromUDP(b)
if err != nil {
log.Println("<-", addr, "Message error:", err)
continue
}
msg := bytes.TrimSpace(b[:n])
log.Printf("<- %q from %s", msg, addr)
for i, l := 0, len(msg); i < l/2; i++ {
msg[i], msg[l-1-i] = msg[l-1-i], msg[i]
}
msg = append(msg, ' ')
if _, err := conn.WriteTo(b[:n], addr); err != nil {
log.Println("->", addr, "Send error:", err)
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225