package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
service := ":1200"
udpAddr, err := net.ResolveUDPAddr("udp4", service)
checkError(err)
conn, err := net.ListenUDP("udp", udpAddr)
checkError(err)
for {
handleClient(conn)
}
}
func handleClient(conn *net.UDPConn) {
var buf [512]byte
_, addr, err := conn.ReadFromUDP(buf[0:])
if err != nil {
return
}
daytime := time.Now().String()
conn.WriteToUDP([]byte(daytime), addr)
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
os.Exit(1)
}
}
试着用 go
关键字
for {
go handleClient(conn)
}
引起系统 load average 过高到 400 over. 同时 client 只能响应一个请求。
1
sakeven 2015-10-19 19:24:34 +08:00 via iPhone
go handleclient
|
2
jjjabc 2015-10-19 20:27:09 +08:00
main 里面不要用 go ,在 handleClient 里面用
func handleClient(conn *net.UDPConn) { var buf [512]byte _, addr, err := conn.ReadFromUDP(buf[0:]) if err != nil { return } go { daytime := time.Now().String() conn.WriteToUDP([]byte(daytime), addr) } } |
3
jjjabc 2015-10-19 20:33:41 +08:00
回复能用 Markdown ?
``` func handleClient(conn *net.UDPConn) { var buf [512]byte _, addr, err := conn.ReadFromUDP(buf[0:]) if err != nil { return } go { daytime := time.Now().String() conn.WriteToUDP([]byte(daytime), addr) } } ``` |