[Go] Simple implementation of a udp server

Original link: https://grimoire.cn/golang/go-udp.html

Preamble

Previous recommendation: [Go] Simple implementation of a tcp server – Five Leaf Magic Book (grimoire.cn)

We explained how to use tcp to implement a simple server in the previous article, so let’s talk about how to use udp to implement a simple udp server today

As usual, let’s talk about the basics of the udp protocol first:

  1. The udp protocol and tcp belong to the same transport layer protocol, and it is also a protocol established on top of ip (transport layer), which has also been implemented at the operating system level.
  2. udp protocol is connectionless, best effort delivery (data may be lost), no congestion control

In actual use, udp is more for scenarios that require high efficiency, because there is no need to establish a connection, and no handshake is required, which saves a lot of time, so it is often used in services such as dns (tftp , webcast, quic), and it is precisely because udp does not require a handshake that it is selected by the http3 standard.

Code

Server

Before implementation, let’s talk about the idea in general:

  1. Because udp does not need to be connection-oriented, we do not need additional coroutines to process separately this time, just use a loop to read data
 /* * @Author: NorthCity1984 * @LastEditTime: 2022-10-19 22:34:48 * @Description: * @Website: https://grimoire.cn * Copyright (c) NorthCity1984 All rights reserved. */ package main import ( "fmt" "log" "net" ) func main() { // 启动一个udp 服务listen, err := net.ListenUDP("udp", &net.UDPAddr{Port: 3000}) if err != nil { log.Fatalln(err) } defer listen.Close() buffer := make([]byte, 256) for { // 循环读取数据n, addr, err := listen.ReadFromUDP(buffer) if err != nil { log.Println(err) return } fmt.Println("addr: ", addr, "message: ", string(buffer[:n])) } }

client

For the client’s idea, we still refer to the previous tcp client, and the basic structure is almost the same.

 /* * @Author: NorthCity1984 * @LastEditTime: 2022-10-19 22:34:31 * @Description: * @Website: https://grimoire.cn * Copyright (c) NorthCity1984 All rights reserved. */ package main import ( "fmt" "log" "net" ) func main() { listen, err := net.DialUDP("udp", nil, &net.UDPAddr{Port: 3000}) if err != nil { log.Fatalln(err) } defer listen.Close() for { var input string fmt.Scan(&input) _, err := listen.Write([]byte(input)) if err != nil { log.Println(err) break } } }

This article is reprinted from: https://grimoire.cn/golang/go-udp.html
This site is for inclusion only, and the copyright belongs to the original author.