github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/examples/tcp_echo/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "net" 7 "os" 8 "sync/atomic" 9 "time" 10 11 "github.com/pawelgaczynski/gain" 12 "github.com/pawelgaczynski/gain/logger" 13 "github.com/rs/zerolog" 14 ) 15 16 const ( 17 port = 8080 18 numberOfClients = 2 19 ) 20 21 var testData = []byte("echo") 22 23 type EventHandler struct { 24 server gain.Server 25 26 logger zerolog.Logger 27 28 overallBytesSent atomic.Uint64 29 } 30 31 func (e *EventHandler) OnStart(server gain.Server) { 32 e.server = server 33 e.logger = zerolog.New(os.Stdout).With().Logger().Level(zerolog.InfoLevel) 34 } 35 36 func (e *EventHandler) OnAccept(conn gain.Conn) { 37 e.logger.Info(). 38 Int("active connections", e.server.ActiveConnections()). 39 Str("remote address", conn.RemoteAddr().String()). 40 Msg("New connection accepted") 41 } 42 43 func (e *EventHandler) OnRead(conn gain.Conn, n int) { 44 e.logger.Info(). 45 Int("bytes", n). 46 Str("remote address", conn.RemoteAddr().String()). 47 Msg("Bytes received from remote peer") 48 49 var ( 50 err error 51 buffer []byte 52 ) 53 54 buffer, err = conn.Next(n) 55 if err != nil { 56 return 57 } 58 59 _, _ = conn.Write(buffer) 60 } 61 62 func (e *EventHandler) OnWrite(conn gain.Conn, n int) { 63 e.overallBytesSent.Add(uint64(n)) 64 65 e.logger.Info(). 66 Int("bytes", n). 67 Str("remote address", conn.RemoteAddr().String()). 68 Msg("Bytes sent to remote peer") 69 70 err := conn.Close() 71 if err != nil { 72 e.logger.Error().Err(err).Msg("Error during connection close") 73 } 74 } 75 76 func (e *EventHandler) OnClose(conn gain.Conn, err error) { 77 log := e.logger.Info(). 78 Str("remote address", conn.RemoteAddr().String()) 79 if err != nil { 80 log.Err(err).Msg("Connection from remote peer closed") 81 } else { 82 log.Msg("Connection from remote peer closed by server") 83 } 84 85 if e.overallBytesSent.Load() >= uint64(len(testData)*numberOfClients) { 86 e.server.AsyncShutdown() 87 } 88 } 89 90 func runClients() { 91 for i := 0; i < numberOfClients; i++ { 92 go func() { 93 time.Sleep(time.Second) 94 95 conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), time.Second) 96 if err != nil { 97 log.Panic(err) 98 } 99 100 n, err := conn.Write(testData) 101 if err != nil { 102 log.Panic() 103 } 104 105 if n != len(testData) { 106 log.Panic() 107 } 108 109 buffer := make([]byte, len(testData)) 110 111 n, err = conn.Read(buffer) 112 if err != nil { 113 log.Panic() 114 } 115 116 if n != len(testData) { 117 log.Panic() 118 } 119 }() 120 } 121 } 122 123 func main() { 124 runClients() 125 126 err := gain.ListenAndServe( 127 fmt.Sprintf("tcp://127.0.0.1:%d", port), &EventHandler{}, gain.WithLoggerLevel(logger.WarnLevel)) 128 if err != nil { 129 log.Panic(err) 130 } 131 }