github.com/lirm/aeron-go@v0.0.0-20230415210743-920325491dc4/examples/basic_rpc/server/basic_server.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  	"flag"
    21  	"fmt"
    22  	"log"
    23  	"os"
    24  	"os/signal"
    25  	"syscall"
    26  	"time"
    27  
    28  	"github.com/lirm/aeron-go/aeron"
    29  	"github.com/lirm/aeron-go/aeron/atomic"
    30  	"github.com/lirm/aeron-go/aeron/idlestrategy"
    31  	"github.com/lirm/aeron-go/aeron/logbuffer"
    32  	"github.com/lirm/aeron-go/aeron/logging"
    33  	"github.com/lirm/aeron-go/examples"
    34  )
    35  
    36  var logger = logging.MustGetLogger("basic_server")
    37  
    38  var interrupt = make(chan os.Signal, 1)
    39  
    40  func init() {
    41  	signal.Notify(interrupt, os.Interrupt)
    42  	signal.Notify(interrupt, syscall.SIGTERM)
    43  }
    44  
    45  type client struct {
    46  	pub *aeron.Publication
    47  }
    48  
    49  func main() {
    50  	flag.Parse()
    51  
    52  	if *examples.ExamplesConfig.LoggingOn {
    53  		logging.SetLevel(logging.INFO, "aeron")
    54  		logging.SetLevel(logging.INFO, "memmap")
    55  		logging.SetLevel(logging.DEBUG, "driver")
    56  		logging.SetLevel(logging.INFO, "counters")
    57  		logging.SetLevel(logging.INFO, "logbuffers")
    58  		logging.SetLevel(logging.INFO, "buffer")
    59  	}
    60  
    61  	to := time.Duration(time.Millisecond.Nanoseconds() * *examples.ExamplesConfig.DriverTo)
    62  	ctx := aeron.NewContext().AeronDir(*examples.ExamplesConfig.AeronPrefix).MediaDriverTimeout(to)
    63  
    64  	a, err := aeron.Connect(ctx)
    65  	if err != nil {
    66  		logger.Fatalf("Failed to connect to media driver: %s\n", err.Error())
    67  	}
    68  	defer a.Close()
    69  
    70  	subscription, err := a.AddSubscription(*examples.ExamplesConfig.Channel, int32(*examples.ExamplesConfig.StreamID))
    71  	if err != nil {
    72  		logger.Fatal(err)
    73  	}
    74  	defer subscription.Close()
    75  	log.Printf("Subscription found %v", subscription)
    76  
    77  	clients := make(map[int32]*client)
    78  	defer func() {
    79  		for _, c := range clients {
    80  			c.pub.Close()
    81  		}
    82  	}()
    83  
    84  	handler := func(buffer *atomic.Buffer, offset int32, length int32, header *logbuffer.Header) {
    85  		bytes := buffer.GetBytesArray(offset, length)
    86  
    87  		c, found := clients[header.SessionId()]
    88  		if !found {
    89  			pub, err := a.AddExclusivePublication(string(bytes), int32(*examples.ExamplesConfig.StreamID))
    90  			if err != nil {
    91  				logger.Fatal(err)
    92  			}
    93  			c = &client{
    94  				pub: pub,
    95  			}
    96  			clients[header.SessionId()] = c
    97  		}
    98  	}
    99  
   100  	idleStrategy := idlestrategy.Sleeping{SleepFor: time.Millisecond}
   101  
   102  	counter := 0
   103  	for {
   104  		fragmentsRead := subscription.Poll(handler, 10)
   105  
   106  		if counter > *examples.ExamplesConfig.Messages {
   107  			break
   108  		}
   109  		counter++
   110  
   111  		message := fmt.Sprintf("this is a message %d", counter)
   112  		srcBuffer := atomic.MakeBuffer(([]byte)(message))
   113  		for _, c := range clients {
   114  			publication := c.pub
   115  			ret := publication.Offer(srcBuffer, 0, int32(len(message)), nil)
   116  			switch ret {
   117  			case aeron.NotConnected:
   118  				log.Printf("%d: not connected yet", counter)
   119  			case aeron.BackPressured:
   120  				log.Printf("%d: back pressured", counter)
   121  			default:
   122  				if ret < 0 {
   123  					log.Printf("%d: Unrecognized code: %d", counter, ret)
   124  				} else {
   125  					log.Printf("%d: success!", counter)
   126  				}
   127  			}
   128  
   129  			if !publication.IsConnected() {
   130  				log.Printf("no subscribers detected")
   131  			}
   132  		}
   133  		idleStrategy.Idle(fragmentsRead)
   134  		select {
   135  		case <-interrupt:
   136  			return
   137  		default:
   138  			time.Sleep(time.Second)
   139  		}
   140  	}
   141  }