nanomsg.org/go/mangos/v2@v2.0.9-0.20200203084354-8a092611e461/examples/raw/server.go (about)

     1  // Copyright 2018 The Mangos Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use file except in compliance with the License.
     5  // You may obtain a copy of the license at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"encoding/binary"
    19  	"fmt"
    20  	"math/rand"
    21  	"sync"
    22  	"time"
    23  
    24  	"nanomsg.org/go/mangos/v2"
    25  	"nanomsg.org/go/mangos/v2/protocol/xrep"
    26  
    27  	// register transports
    28  	_ "nanomsg.org/go/mangos/v2/transport/all"
    29  )
    30  
    31  // Our protocol is simple.  Request packet is empty.  The reply
    32  // is the replier's ID and the time it delayed responding for (us).
    33  
    34  func serverWorker(sock mangos.Socket, id int) {
    35  	var err error
    36  
    37  	delay := rand.Intn(int(time.Second))
    38  
    39  	for {
    40  		var m *mangos.Message
    41  
    42  		if m, err = sock.RecvMsg(); err != nil {
    43  			return
    44  		}
    45  
    46  		m.Body = make([]byte, 4)
    47  
    48  		time.Sleep(time.Duration(delay))
    49  
    50  		binary.BigEndian.PutUint32(m.Body[0:], uint32(id))
    51  
    52  		if err = sock.SendMsg(m); err != nil {
    53  			return
    54  		}
    55  	}
    56  }
    57  
    58  func server(url string, nworkers int) {
    59  	var sock mangos.Socket
    60  	var err error
    61  	var wg sync.WaitGroup
    62  
    63  	rand.Seed(time.Now().UnixNano())
    64  
    65  	if sock, err = xrep.NewSocket(); err != nil {
    66  		die("can't get new rep socket: %s", err)
    67  	}
    68  	if err = sock.Listen(url); err != nil {
    69  		die("can't listen on rep socket: %s", err.Error())
    70  	}
    71  	wg.Add(nworkers)
    72  	fmt.Printf("Starting %d workers\n", nworkers)
    73  	for id := 0; id < nworkers; id++ {
    74  		go func(id int) {
    75  			defer wg.Done()
    76  			serverWorker(sock, id)
    77  		}(id)
    78  	}
    79  	wg.Wait()
    80  }