github.com/lirm/aeron-go@v0.0.0-20230415210743-920325491dc4/examples/basic_subscriber/basic_subscriber.go (about) 1 /* 2 Copyright 2016 Stanislav Liberman 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "bytes" 21 "flag" 22 "fmt" 23 "log" 24 "time" 25 26 "github.com/lirm/aeron-go/aeron" 27 "github.com/lirm/aeron-go/aeron/atomic" 28 "github.com/lirm/aeron-go/aeron/idlestrategy" 29 "github.com/lirm/aeron-go/aeron/logbuffer" 30 "github.com/lirm/aeron-go/aeron/logging" 31 "github.com/lirm/aeron-go/examples" 32 ) 33 34 var logger = logging.MustGetLogger("basic_subscriber") 35 36 func main() { 37 flag.Parse() 38 39 if !*examples.ExamplesConfig.LoggingOn { 40 logging.SetLevel(logging.INFO, "aeron") 41 logging.SetLevel(logging.INFO, "memmap") 42 logging.SetLevel(logging.DEBUG, "driver") 43 logging.SetLevel(logging.INFO, "counters") 44 logging.SetLevel(logging.INFO, "logbuffers") 45 logging.SetLevel(logging.INFO, "buffer") 46 } 47 48 to := time.Duration(time.Millisecond.Nanoseconds() * *examples.ExamplesConfig.DriverTo) 49 ctx := aeron.NewContext().AeronDir(*examples.ExamplesConfig.AeronPrefix).MediaDriverTimeout(to) 50 51 a, err := aeron.Connect(ctx) 52 if err != nil { 53 logger.Fatalf("Failed to connect to media driver: %s\n", err.Error()) 54 } 55 defer a.Close() 56 57 subscription, err := a.AddSubscription(*examples.ExamplesConfig.Channel, int32(*examples.ExamplesConfig.StreamID)) 58 if err != nil { 59 logger.Fatal(err) 60 } 61 defer subscription.Close() 62 log.Printf("Subscription found %v", subscription) 63 64 tmpBuf := &bytes.Buffer{} 65 counter := 1 66 handler := func(buffer *atomic.Buffer, offset int32, length int32, header *logbuffer.Header) { 67 bytes := buffer.GetBytesArray(offset, length) 68 tmpBuf.Reset() 69 buffer.WriteBytes(tmpBuf, offset, length) 70 fmt.Printf("%8.d: Gots me a fragment offset:%d length: %d payload: %s (buf:%s)\n", counter, offset, length, string(bytes), string(tmpBuf.Next(int(length)))) 71 72 counter++ 73 } 74 75 idleStrategy := idlestrategy.Sleeping{SleepFor: time.Millisecond} 76 77 for { 78 fragmentsRead := subscription.Poll(handler, 10) 79 idleStrategy.Idle(fragmentsRead) 80 } 81 }