Go Socket UDP
UDP is a connectionless transport layer protocol that does not guarantee reliable transmission of messages, which may lead to issues such as data loss and out-of-order delivery. However, UDP boasts excellent real-time performance and is commonly used in areas related to live video streaming and the like.
UDP Server
import (
"fmt"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:8081")
if err != nil {
fmt.Println("Error resolving UDP address:", err)
return
}
//Listen on a port
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer conn.Close()
fmt.Println("Listening on: 8081")
for {
handle(conn)
}
}
func handle(conn *net.UDPConn) {
//Set up a buffer for reading data
buffer := make([]byte, 1024)
for {
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading from:", err)
break
}
//Receive data from clients
fmt.Printf("Received from %s: %s\n", addr, string(buffer[:n]))
//Send responses to clients
_, err = conn.WriteToUDP([]byte("Welcome "+addr.String()), addr)
if err != nil {
fmt.Println("Error writing to the client:", err)
}
}
}
UDP Client
import (
"bufio"
"fmt"
"net"
"os"
"strings"
"time"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:8081")
if err != nil {
fmt.Println("Error resolving UDP address:", err)
return
}
//Connect to the server
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
fmt.Println("Error connecting to:", err)
return
}
defer conn.Close()
//Read user input
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter message: ")
message, _ := reader.ReadString('\n')
//Trim whitespace characters (e.g., spaces, tabs, newlines) before sending messages
message = strings.TrimSpace(message)
if message == "exit" || message == "quit" {
return
}
//Send messages to the server
_, err = conn.Write([]byte(message))
if err != nil {
fmt.Println("Error writing to UDP:", err)
return
}
//Optionally, read responses from the server, noting that due to UDP's connectionless nature,
//there's no guarantee that the server will respond or that the response will arrive on time
buffer := make([]byte, 1024)
//Because UDP is connectionless, set a read timeout to prevent the ReadFromUDP method from potentially blocking indefinitely waiting for data.
conn.SetReadDeadline(time.Now().Add(time.Second * 3))
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading from:", err)
return
}
fmt.Printf("Received from server %s: %s\n", addr, string(buffer[:n]))
}
}
Take a break
πππ γJade Dynasty EP48γLu Xueqi expressed her love to Gui Li, and danced a sword dance for him