Created
January 1, 2020 12:10
-
-
Save erikdubbelboer/d493450f38a77fc74b57f4a1cd4f7380 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
"sync/atomic" | |
"time" | |
) | |
var ( | |
duration = int64(0) | |
count = int64(0) | |
connections = int64(0) | |
responseDelay = time.Millisecond * 200 // Wait 200ms before sending the response. | |
) | |
func handler(c net.Conn) { | |
buff := make([]byte, 4) | |
for { | |
if _, err := c.Read(buff); err != nil { | |
panic(err) | |
} | |
if _, err := c.Write(buff); err != nil { | |
panic(err) | |
} | |
} | |
} | |
func listener(ln net.Listener) { | |
for { | |
c, err := ln.Accept() | |
if err != nil { | |
panic(err) | |
} | |
go handler(c) | |
} | |
} | |
func worker() { | |
c, err := net.Dial("tcp", "127.0.0.1:5555") | |
if err != nil { | |
panic(err) | |
} | |
atomic.AddInt64(&connections, 1) | |
buff := []byte{1, 2, 3, 4} | |
for { | |
start := time.Now() | |
if _, err := c.Write(buff); err != nil { | |
panic(err) | |
} | |
if _, err := c.Read(buff); err != nil { | |
panic(err) | |
} | |
d := int64(time.Since(start)) | |
atomic.AddInt64(&duration, d) | |
atomic.AddInt64(&count, 1) | |
time.Sleep(responseDelay) | |
} | |
} | |
func startup() { | |
for i := 0; i < 9000; i++ { | |
go worker() | |
time.Sleep(time.Millisecond * 4) | |
} | |
} | |
func main() { | |
ln, err := net.Listen("tcp", "127.0.0.1:5555") | |
if err != nil { | |
panic(err) | |
} | |
go listener(ln) | |
go startup() | |
for { | |
time.Sleep(time.Second) | |
n := atomic.LoadInt64(&connections) | |
d := atomic.SwapInt64(&duration, 0) | |
c := atomic.SwapInt64(&count, 0) | |
if c > 0 { | |
fmt.Printf("connections: % 4d latency: % 12v (requests: %d)\n", n, time.Duration(d/c), c) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment