Strange golang UDP server behavior

I wrote a simple UDP server in go.

When I do go run udp.go , it prints all the packages I sent. But when you run go run udp.go > out it stops passing stdout to the out file when the client stops.

Client is a simple program that sends 10k requests. Therefore, in the file I have about 50% of the packages sent. When I run the client again, the out file will grow again until the client script finishes.

Server Code:

 package main import ( "net" "fmt" ) func main() { addr, _ := net.ResolveUDPAddr("udp", ":2000") sock, _ := net.ListenUDP("udp", addr) i := 0 for { i++ buf := make([]byte, 1024) rlen, _, err := sock.ReadFromUDP(buf) if err != nil { fmt.Println(err) } fmt.Println(string(buf[0:rlen])) fmt.Println(i) //go handlePacket(buf, rlen) } } 

And here is the client code:

 package main import ( "net" "fmt" ) func main() { num := 0 for i := 0; i < 100; i++ { for j := 0; j < 100; j++ { num++ con, _ := net.Dial("udp", "127.0.0.1:2000") fmt.Println(num) buf := []byte("bla bla bla I am the packet") _, err := con.Write(buf) if err != nil { fmt.Println(err) } } } } 
+7
go udp networking
source share
2 answers

As you suspected, this is similar to the loss of UDP packets due to the nature of UDP. Since UDP does not require a connection, the client does not care if the server is available or ready to receive data. Therefore, if the server is busy with processing, it will not be available to process the next incoming datagram. You can check with netstat -u (which should include information about UDP packet loss). I came across the same one in which the server (the receiving side) could not keep up with the sent packets.

You can try two things (the second worked for me with your example):

Call SetReadBuffer. Make sure the receiving socket has enough buffering to handle anything you throw at it.

 sock, _ := net.ListenUDP("udp", addr) sock.SetReadBuffer(1048576) 

Perform all packet processing in the normal procedure. Try increasing the number of datagrams per second, ensuring that the server is not busy with other work when you want it to be available for reception. those. move processing to a routine, so you don't delay ReadFromUDP ().

 //Reintroduce your go handlePacket(buf, rlen) with a count param func handlePacket(buf []byte, rlen int, count int) fmt.Println(string(buf[0:rlen])) fmt.Println(count) } 

...

 go handlePacket(buf, rlen, i) 

One final option:

Finally, and perhaps not what you want, you put it to sleep in your client , which will slow down the speed and also fix the problem. eg

 buf := []byte("bla bla bla I am the packet") time.Sleep(100 * time.Millisecond) _, err := con.Write(buf) 
+11
source share

Try synchronizing stdout after write statements.

 os.Stdout.Sync() 
+1
source share

All Articles