本文整理汇总了Golang中github.com/pebbe/zmq4.Socket.Bind方法的典型用法代码示例。如果您正苦于以下问题:Golang Socket.Bind方法的具体用法?Golang Socket.Bind怎么用?Golang Socket.Bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/pebbe/zmq4.Socket
的用法示例。
在下文中一共展示了Socket.Bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: bind
func bind(socket *zmq.Socket, transport string, address string, port int) {
endpoint := fmt.Sprintf("%s://%s:%d", transport, address, port)
err := socket.Bind(endpoint)
if err != nil {
die("failed binding %s: %s", endpoint, err.Error())
}
}
示例2: StartZeromqProtoRepServer
func StartZeromqProtoRepServer(port string) {
var socket *zmq.Socket
var err error
if socket, err = zmq.NewSocket(zmq.REP); err != nil {
log.Fatal(err)
}
if err = socket.Bind("tcp://0.0.0.0:" + port); err != nil {
log.Fatal(err)
}
for {
request, _ := socket.RecvBytes(0)
var body pb.Request
proto.Unmarshal(request, &body)
response, _ := proto.Marshal(&pb.Response{
Method: body.Method,
PayloadLength: int64(len(body.Payload)),
})
socket.SendBytes(response, 0)
}
}
示例3: createSendAndReceivingSocket
/************************************************************
Creates Sockets for Sending and Receiving purpose
*************************************************************/
func createSendAndReceivingSocket(configFile string, selfPort int) ([]*zmq.Socket, *zmq.Socket) {
file, e := ioutil.ReadFile("./" + configFile)
if e != nil {
fmt.Printf("Raft Test File error: %v\n", e)
os.Exit(1)
}
var jsontype jsonobject
json.Unmarshal(file, &jsontype)
elementCount := len(jsontype.Server)
sendConnections := make([]*zmq.Socket, elementCount)
tempId := 0
for _, value := range jsontype.Server {
sendConnections[tempId], _ = zmq.NewSocket(zmq.PUSH)
sendConnections[tempId].Connect("tcp://localhost:" + strconv.Itoa(value.Port_Num+1))
tempId++
}
var receiveConnection *zmq.Socket
receiveConnection, _ = zmq.NewSocket(zmq.PULL)
receiveConnection.Bind("tcp://*:" + strconv.Itoa(selfPort))
return sendConnections, receiveConnection
}
示例4: New
func New(id int, f string) Cluster {
var myid int
var peer [MAX_SERVER]int
var cluster [MAX_SERVER]*zmq.Socket
var mycluster *zmq.Socket
var no_of_p int
file, _ := ioutil.ReadFile(f)
var jsontype jsonobject
json.Unmarshal(file, &jsontype)
myid = id
no_of_p = jsontype.Object.Buffer_size
for i := 0; i < jsontype.Object.Buffer_size; i++ {
if jsontype.Object.Peers[i].Id != myid {
peer[i] = jsontype.Object.Peers[i].Id
cluster[i], _ = zmq.NewSocket(zmq.PUSH)
cluster[i].Connect("tcp://" + jsontype.Object.Peers[i].Host)
} else {
mycluster, _ = zmq.NewSocket(zmq.PULL)
mycluster.SetIdentity(string(id))
a := strings.Split(jsontype.Object.Peers[i].Host, ":")
mycluster.Bind("tcp://*:" + a[1])
}
}
return Cluster{myid: id, peer: peer, no_of_peer: no_of_p, my_cluster: mycluster, cluster: cluster, inbox: make(chan *Envelope, BUFFER_LENGTH_IN), outbox: make(chan *Envelope, BUFFER_LENGTH_OUT)}
}
示例5: New
func New(serverid int, filename string) Servernode {
var data serverlist
content, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
err = json.Unmarshal(content, &data)
if err != nil {
panic("Error parsing json File")
}
mapofservers = make(map[int]int)
for i := 0; i < len(data.RunningServer); i++ {
mapofservers[data.RunningServer[i].Serverid] = data.RunningServer[i].Portno
}
var s Servernode
s.peers = make(map[int]int)
s.peersocks = make(map[int]*zmq.Socket)
_, exist := mapofservers[serverid]
if exist != true {
panic("Error in creation of new server instance")
}
s.sid = serverid
s.pid = mapofservers[serverid]
s.outbox = make(chan *Envelope)
s.inbox = make(chan *Envelope)
var responder *zmq.Socket
var requester *zmq.Socket
for id, port := range mapofservers {
if id == serverid {
responder, err = zmq.NewSocket(zmq.PULL)
s.Ownsocks = responder
responder.Bind("tcp://*:" + strconv.Itoa(port))
if err != nil {
panic("Problem Binding Server")
}
} else {
requester, err = zmq.NewSocket(zmq.PUSH)
if err != nil {
panic("Problem Binding Server")
}
requester.Connect("tcp://localhost:" + strconv.Itoa(port))
s.peers[id] = port
s.peersocks[port] = requester
}
}
go s.SendMessage()
go s.RecieveMessage(responder)
return s
}
示例6: applyZMQConfig
func applyZMQConfig(socket *zmq.Socket, configs []ZMQConfig) {
for _, config := range configs {
switch config.Type {
case "bind":
socket.Bind(config.Uri)
case "connect":
socket.Connect(config.Uri)
}
}
}
示例7: serveZMQ
// serveZMQ
func serveZMQ(zmqPort int, channelStr chan string, metrics metricContainer) {
var zmqListener *zmq.Socket
if channelStr == nil {
listenerURL := "*:" + strconv.Itoa(zmqPort)
fmt.Println("ZeroMQ listening on port: " + listenerURL)
zmqListener, _ = zmq.NewSocket(zmq.PULL)
defer zmqListener.Close()
zmqListener.Bind("tcp://" + listenerURL)
}
for {
var msg string
if channelStr == nil {
// Wait for next request from client
var err error
msg, err = zmqListener.Recv(0)
if err != nil {
fmt.Printf("Error in receive: %v", err)
break
}
} else {
msg = <-channelStr
}
// unmarshall bulked data
var bulk []string
err := json.Unmarshal([]byte(msg), &bulk)
if err != nil {
fmt.Println("json unmarshall error:", err)
}
// extra data
for _, data := range bulk {
dtime, _ := utils.ParseDate4(data[:19])
//dtime, err := time.Parse(dtFormat, data[:19]) // date time
if err != nil {
fmt.Println("time.Parse error:", err)
}
value := data[20:]
intval, _ := strconv.Atoi(value)
m := metric{dtime, intval}
metrics.AddMetric(&m)
//fmt.Println("At ", dtime, " value=", value)
}
}
}
示例8: TestSocketEvent
func TestSocketEvent(t *testing.T) {
var rep *zmq.Socket
defer func() {
if rep != nil {
rep.SetLinger(0)
rep.Close()
}
}()
// REP socket
rep, err := zmq.NewSocket(zmq.REP)
if err != nil {
t.Fatal("NewSocket:", err)
}
// REP socket monitor, all events
err = rep.Monitor("inproc://monitor.rep", zmq.EVENT_ALL)
if err != nil {
t.Fatal("rep.Monitor:", err)
}
chMsg := make(chan string, 10)
go rep_socket_monitor("inproc://monitor.rep", chMsg)
time.Sleep(time.Second)
// Generate an event
err = rep.Bind("tcp://*:9689")
if err != nil {
t.Fatal("rep.Bind:", err)
}
rep.Close()
rep = nil
expect := []string{
"EVENT_LISTENING tcp://0.0.0.0:9689",
"EVENT_CLOSED tcp://0.0.0.0:9689",
"Done",
}
i := 0
for msg := range chMsg {
if i < len(expect) {
if msg != expect[i] {
t.Errorf("Expected message %q, got %q", expect[i], msg)
}
i++
} else {
t.Error("Unexpected message: %q", msg)
}
}
for ; i < len(expect); i++ {
t.Errorf("Expected message %q, got nothing", expect[i])
}
}
示例9: main
// main entry point for data writer
func main() {
var err error
var writerSocket *zmq4.Socket
var eventSubSocket *zmq4.Socket
fog.Info("program starts")
if writerSocket, err = createWriterSocket(); err != nil {
fog.Critical("createWriterSocket %s", err)
}
defer writerSocket.Close()
fog.Info("binding writer socket to %s", dataWriterAddress)
if err = writerSocket.Bind(dataWriterAddress); err != nil {
fog.Critical("Bind(%s) %s", dataWriterAddress, err)
}
if eventSubSocket, err = createEventSubSocket(); err != nil {
fog.Critical("createEventSubSocket %s", err)
}
defer eventSubSocket.Close()
fog.Info("connecting event sub socket to %s", eventAggregatorPubAddress)
if err = eventSubSocket.Connect(eventAggregatorPubAddress); err != nil {
fog.Critical("Connect(%s) %s", eventAggregatorPubAddress, err)
}
messageChan := NewMessageHandler()
reactor := zmq4.NewReactor()
reactor.AddChannel(tools.NewSignalWatcher(), 1, tools.SigtermHandler)
reactor.AddSocket(writerSocket, zmq4.POLLIN,
NewWriterSocketHandler(writerSocket, messageChan))
reactor.AddSocket(eventSubSocket, zmq4.POLLIN,
NewEventSubSocketHandler(eventSubSocket))
fog.Debug("starting reactor.Run")
reactor.SetVerbose(true)
err = reactor.Run(reactorPollingInterval)
if err == tools.SigtermError {
fog.Info("program terminates normally due to SIGTERM")
} else if errno, ok := err.(syscall.Errno); ok {
// we can get 'interrupted system call' if we get SIGTERM while
// a socket is waiting on a read. That's not too bad.
if errno == syscall.EINTR {
fog.Warn("reactor.Run returns '%s' assuming SIGTERM", errno)
} else {
fog.Error("reactor.Run returns %T '%s'", errno, errno)
}
} else {
fog.Error("reactor.Run returns %T %s", err, err)
}
}
示例10: TestPairTcp
func TestPairTcp(t *testing.T) {
var sb, sc *zmq.Socket
defer func() {
for _, s := range []*zmq.Socket{sb, sc} {
if s != nil {
s.SetLinger(0)
s.Close()
}
}
}()
sb, err := zmq.NewSocket(zmq.PAIR)
if err != nil {
t.Fatal("NewSocket:", err)
}
err = sb.Bind("tcp://127.0.0.1:9736")
if err != nil {
t.Fatal("sb.Bind:", err)
}
sc, err = zmq.NewSocket(zmq.PAIR)
if err != nil {
t.Fatal("NewSocket:", err)
}
err = sc.Connect("tcp://127.0.0.1:9736")
if err != nil {
t.Fatal("sc.Connect:", err)
}
msg, err := bounce(sb, sc)
if err != nil {
t.Error(msg, err)
}
err = sc.Close()
sc = nil
if err != nil {
t.Error("sc.Close:", err)
}
err = sb.Close()
sb = nil
if err != nil {
t.Error("sb.Close:", err)
}
}
示例11: ApplyZeroMQConfigs
func ApplyZeroMQConfigs(socket *zmq.Socket, configs []*ZeroMQConfig) (err error) {
for _, config := range configs {
switch config.Mode {
case "connect":
err = socket.Connect(config.URI)
case "bind":
err = socket.Bind(config.URI)
default:
err = errUnknownZeroMQMode
}
if err != nil {
return
}
}
return
}
示例12: bind
func bind(sock *zmq.Socket, endpoint string) (string, uint16, error) {
var port uint16
e, err := url.Parse(endpoint)
if err != nil {
return endpoint, 0, err
}
if e.Scheme == "inproc" {
err = sock.Bind(endpoint)
return endpoint, 0, err
}
ip, p, err := net.SplitHostPort(e.Host)
if err != nil {
return endpoint, 0, err
}
if p == "*" {
for i := dynPortFrom; i <= dynPortTo; i++ {
rand.Seed(time.Now().UTC().UnixNano())
port = uint16(rand.Intn(int(dynPortTo-dynPortFrom))) + dynPortFrom
endpoint = fmt.Sprintf("%s://%s:%d", e.Scheme, ip, port)
err = sock.Bind(endpoint)
if err == nil {
break
} else if err.Error() == "no sock.ch device" {
port = 0
err = fmt.Errorf("no sock.ch device: %s", endpoint)
break
} else if i-dynPortFrom > 100 {
err = errors.New("Unable to bind to an ephemeral port")
break
}
}
return endpoint, port, err
}
pp, err := strconv.ParseUint(p, 10, 16)
if err != nil {
return endpoint, 0, err
}
port = uint16(pp)
err = sock.Bind(endpoint)
return endpoint, port, err
}
示例13: TestZmqChanSocket
func TestZmqChanSocket(t *testing.T) {
var sb, sc *zmq.Socket
var cb, cc zmqchan.ChanSocket
var err error
num := 10
defer func() {
if sb != nil {
sb.SetLinger(0)
sb.Close()
}
if sc != nil {
sc.SetLinger(0)
sc.Close()
}
if cb != nil {
log.Println("MAIN: Close")
cb.Close()
}
if cc != nil {
log.Println("ECHO: Close")
cc.Close()
}
log.Println("BOTH: Exit")
}()
if sb, err = zmq.NewSocket(zmq.PAIR); err != nil {
t.Fatal("NewSocket:", err)
}
if sc, err = zmq.NewSocket(zmq.PAIR); err != nil {
t.Fatal("NewSocket:", err)
}
if err = sb.Bind("tcp://127.0.0.1:9737"); err != nil {
t.Fatal("sb.Bind:", err)
}
if err = sc.Connect("tcp://127.0.0.1:9737"); err != nil {
t.Fatal("sc.Connect:", err)
}
if cb, err = zmqchan.NewZmqChanSocket(sb, 0, 0); err != nil {
t.Fatal("sb.NewZmqChanSocket:", err)
}
sb = nil // don't access this or close it on defer
if cc, err = zmqchan.NewZmqChanSocket(sc, 0, 0); err != nil {
t.Fatal("sb.NewZmqChanSocket:", err)
}
sc = nil // don't access this or close it on defer
var wg sync.WaitGroup
wg.Add(1)
go func() {
runEcho(t, num, cc)
wg.Done()
}()
wg.Add(1)
go func() {
runWrite(t, num, cb)
wg.Done()
}()
wg.Wait()
log.Println("BOTH: done")
}
示例14: main
func main() {
flag.Parse(nil)
address_list := flag.Args
if len(address_list) == 0 {
fmt.Println("No Addresses submitted")
fmt.Println(flag.Help())
return
}
var send, recv bool
skip := false
var socket *zmq.Socket
switch *socket_type {
case "PUSH":
socket, _ = zmq.NewSocket(zmq.PUSH)
send = true
case "PULL":
socket, _ = zmq.NewSocket(zmq.PULL)
recv = true
case "PUB":
socket, _ = zmq.NewSocket(zmq.PUB)
send = true
case "SUB":
socket, _ = zmq.NewSocket(zmq.SUB)
recv = true
if len(*subscriptions) == 0 {
socket.SetSubscribe("")
}
for _, subscription := range *subscriptions {
socket.SetSubscribe(subscription)
}
case "REQ":
socket, _ = zmq.NewSocket(zmq.REQ)
send = true
recv = true
case "REP":
socket, _ = zmq.NewSocket(zmq.REP)
send = true
recv = true
skip = true
}
defer socket.Close()
// connect or bind
if *mode {
for _, address := range address_list {
socket.Connect(address)
}
} else {
for _, address := range address_list {
socket.Bind(address)
}
}
delim := byte('\n')
if *null {
fmt.Println("Setting delim to null")
delim = byte(0x00)
}
reader := bufio.NewReader(os.Stdin)
writer := bufio.NewWriter(os.Stdout)
for i := 0; i < *number || *number == -1; i++ {
if send && !skip {
line, _ := reader.ReadBytes(delim)
socket.SendBytes([]byte(line), 0)
}
if recv {
data, _ := socket.RecvBytes(0)
writer.Write(data)
writer.Flush()
}
if skip {
skip = false
}
}
fmt.Println("finished", *number)
}
示例15: TestRemoteEndpoint
func TestRemoteEndpoint(t *testing.T) {
if _, minor, _ := zmq.Version(); minor < 1 {
t.Skip("RemoteEndpoint not avalable in ZeroMQ versions prior to 4.1.0")
}
addr := "tcp://127.0.0.1:9560"
peer := "127.0.0.1"
var rep, req *zmq.Socket
defer func() {
for _, s := range []*zmq.Socket{rep, req} {
if s != nil {
s.SetLinger(0)
s.Close()
}
}
}()
rep, err := zmq.NewSocket(zmq.REP)
if err != nil {
t.Fatal("NewSocket:", err)
}
req, err = zmq.NewSocket(zmq.REQ)
if err != nil {
t.Fatal("NewSocket:", err)
}
if err = rep.Bind(addr); err != nil {
t.Fatal("rep.Bind:", err)
}
if err = req.Connect(addr); err != nil {
t.Fatal("req.Connect:", err)
}
tmp := "test"
if _, err = req.Send(tmp, 0); err != nil {
t.Fatal("req.Send:", err)
}
// get message with peer address (remote endpoint)
msg, props, err := rep.RecvWithMetadata(0, "Peer-Address")
if err != nil {
t.Fatal("rep.RecvWithMetadata:", err)
return
}
if msg != tmp {
t.Errorf("rep.RecvWithMetadata: expected %q, got %q", tmp, msg)
}
if p := props["Peer-Address"]; p != peer {
t.Errorf("rep.RecvWithMetadata: expected Peer-Address == %q, got %q", peer, p)
}
err = rep.Close()
rep = nil
if err != nil {
t.Fatal("rep.Close:", err)
}
err = req.Close()
req = nil
if err != nil {
t.Fatal("req.Close:", err)
}
}