github.com/gdamore/mangos@v1.4.0/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" 25 "nanomsg.org/go-mangos/protocol/rep" 26 "nanomsg.org/go-mangos/transport/ipc" 27 "nanomsg.org/go-mangos/transport/tcp" 28 ) 29 30 // Our protocol is simple. Request packet is empty. The reply 31 // is the replier's ID and the time it delayed responding for (us). 32 33 func serverWorker(sock mangos.Socket, id int) { 34 var err error 35 36 delay := rand.Intn(int(time.Second)) 37 38 for { 39 var m *mangos.Message 40 41 if m, err = sock.RecvMsg(); err != nil { 42 return 43 } 44 45 m.Body = make([]byte, 4) 46 47 time.Sleep(time.Duration(delay)) 48 49 binary.BigEndian.PutUint32(m.Body[0:], uint32(id)) 50 51 if err = sock.SendMsg(m); err != nil { 52 return 53 } 54 } 55 } 56 57 func server(url string, nworkers int) { 58 var sock mangos.Socket 59 var err error 60 var wg sync.WaitGroup 61 62 rand.Seed(time.Now().UnixNano()) 63 64 if sock, err = rep.NewSocket(); err != nil { 65 die("can't get new rep socket: %s", err) 66 } 67 if err = sock.SetOption(mangos.OptionRaw, true); err != nil { 68 die("can't set raw mode: %s", err) 69 } 70 sock.AddTransport(ipc.NewTransport()) 71 sock.AddTransport(tcp.NewTransport()) 72 if err = sock.Listen(url); err != nil { 73 die("can't listen on rep socket: %s", err.Error()) 74 } 75 wg.Add(nworkers) 76 fmt.Printf("Starting %d workers\n", nworkers) 77 for id := 0; id < nworkers; id++ { 78 go func(id int) { 79 defer wg.Done() 80 serverWorker(sock, id) 81 }(id) 82 } 83 wg.Wait() 84 }