nanomsg.org/go/mangos/v2@v2.0.9-0.20200203084354-8a092611e461/examples/raw/client.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 "sync" 21 22 "nanomsg.org/go/mangos/v2" 23 "nanomsg.org/go/mangos/v2/protocol/req" 24 25 // register transports 26 _ "nanomsg.org/go/mangos/v2/transport/all" 27 ) 28 29 // synchronize our output messaging so we don't overlap 30 var lock sync.Mutex 31 32 func clientWorker(url string, id int) { 33 var sock mangos.Socket 34 var m *mangos.Message 35 var err error 36 37 if sock, err = req.NewSocket(); err != nil { 38 die("can't get new req socket: %s", err.Error()) 39 } 40 41 // Leave this in Cooked mode! 42 43 if err = sock.Dial(url); err != nil { 44 die("can't dial on req socket: %s", err.Error()) 45 } 46 47 // send an empty messsage 48 m = mangos.NewMessage(1) 49 if err = sock.SendMsg(m); err != nil { 50 die("can't send request: %s", err.Error()) 51 } 52 53 if m, err = sock.RecvMsg(); err != nil { 54 die("can't recv reply: %s", err.Error()) 55 } 56 sock.Close() 57 58 if len(m.Body) != 4 { 59 die("bad response len: %d", len(m.Body)) 60 } 61 62 worker := binary.BigEndian.Uint32(m.Body[0:]) 63 64 lock.Lock() 65 fmt.Printf("Client: %4d Server: %4d\n", id, worker) 66 lock.Unlock() 67 } 68 69 func client(url string, nworkers int) { 70 71 var wg sync.WaitGroup 72 for i := 0; i < nworkers; i++ { 73 wg.Add(1) 74 go func(i int) { 75 defer wg.Done() 76 clientWorker(url, i) 77 }(i) 78 } 79 wg.Wait() 80 81 }