golang implements a simple udp protocol server and client example
- 2020-06-01 09:59:38
- OfStack
The example of this article describes the implementation of golang simple udp protocol server and client. I will share it with you for your reference as follows:
In fact, udp does not have any concept of server and client. It just sends and receives one by one, which is easy to recognize and understand.
Server:
package main
import (
"fmt"
"net"
)
func main() {
// Create a listener
socket, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: 8080,
})
if err != nil {
fmt.Println(" Listening to the failure !", err)
return
}
defer socket.Close()
for {
// Read the data
data := make([]byte, 4096)
read, remoteAddr, err := socket.ReadFromUDP(data)
if err != nil {
fmt.Println(" Read data failed !", err)
continue
}
fmt.Println(read, remoteAddr)
fmt.Printf("%s\n\n", data)
// To send data
senddata := []byte("hello client!")
_, err = socket.WriteToUDP(senddata, remoteAddr)
if err != nil {
return
fmt.Println(" Sending data failed !", err)
}
}
}
Client:
package main
import (
"fmt"
"net"
)
func main() {
// Create a connection
socket, err := net.DialUDP("udp4", nil, &net.UDPAddr{
IP: net.IPv4(192, 168, 1, 103),
Port: 8080,
})
if err != nil {
fmt.Println(" The connection fails !", err)
return
}
defer socket.Close()
// To send data
senddata := []byte("hello server!")
_, err = socket.Write(senddata)
if err != nil {
fmt.Println(" Sending data failed !", err)
return
}
// Receive data
data := make([]byte, 4096)
read, remoteAddr, err := socket.ReadFromUDP(data)
if err != nil {
fmt.Println(" Read data failed !", err)
return
}
fmt.Println(read, remoteAddr)
fmt.Printf("%s\n", data)
}
I hope this article has been helpful to you in the programming of Go language.