1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| [root@lab103 udp] package main
import ( "fmt" "net" "os" "strconv" "sync" "time" )
func startUDPFileServer(wg *sync.WaitGroup, host string, port int, bufferSize int, filePath string, targetSpeedMbps int) { defer wg.Done()
addr := fmt.Sprintf("%s:%d", host, port) udpAddr, err := net.ResolveUDPAddr("udp", addr) if err != nil { fmt.Printf("Failed to resolve address: %v\n", err) return }
conn, err := net.ListenUDP("udp", udpAddr) if err != nil { fmt.Printf("Failed to listen on %s: %v\n", addr, err) return } defer conn.Close()
fmt.Printf("UDP File server started, listening on %s...\n", addr)
targetSpeedBps := targetSpeedMbps * 1024 * 1024
buffer := make([]byte, bufferSize)
for { n, clientAddr, err := conn.ReadFromUDP(buffer) if err != nil { fmt.Printf("Error receiving data: %v\n", err) continue } request := string(buffer[:n]) fmt.Printf("Received request from %v: %s\n", clientAddr, request)
if request == "GET" { if _, err := os.Stat(filePath); os.IsNotExist(err) { conn.WriteToUDP([]byte("FILE_NOT_FOUND"), clientAddr) fmt.Println("File not found") continue }
file, err := os.Open(filePath) if err != nil { fmt.Printf("Failed to open file: %v\n", err) continue } defer file.Close()
totalSent := 0 startTime := time.Now()
for { n, err := file.Read(buffer) if err != nil { break } _, err = conn.WriteToUDP(buffer[:n], clientAddr) if err != nil { fmt.Printf("Error sending data: %v\n", err) break } totalSent += n
// 控制发送速度 timeElapsed := time.Since(startTime).Seconds() expectedTime := float64(totalSent) / float64(targetSpeedBps) if timeElapsed < expectedTime { time.Sleep(time.Duration(expectedTime-timeElapsed) * time.Second) } }
conn.WriteToUDP([]byte("END"), clientAddr) fmt.Println("File sent successfully") } else { conn.WriteToUDP([]byte("INVALID_REQUEST"), clientAddr) fmt.Println("Invalid request") } } }
func runServersOnMultiplePorts(host string, startPort, endPort int, bufferSize int, filePath string, targetSpeedMbps int) { var wg sync.WaitGroup
for port := startPort; port <= endPort; port++ { wg.Add(1) go startUDPFileServer(&wg, host, port, bufferSize, filePath, targetSpeedMbps) }
wg.Wait() }
func main() { if len(os.Args) != 4 { fmt.Println("Usage: go run server.go <host> <start_port> <end_port>") return }
host := os.Args[1] startPort, err1 := strconv.Atoi(os.Args[2]) endPort, err2 := strconv.Atoi(os.Args[3])
if err1 != nil || err2 != nil { fmt.Println("Invalid port number") return }
runServersOnMultiplePorts(host, startPort, endPort, 1024, "video.mp4", 2) }
|