本文整理汇总了Golang中github.com/pebbe/zmq4.NewSocket函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSocket函数的具体用法?Golang NewSocket怎么用?Golang NewSocket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSocket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Subscribe
// Subscribe will automatically wire up processing of messages for a request address
func Subscribe(reqaddy string, repaddy string) {
reqsock, _ = zmq.NewSocket(zmq.SUB)
defer reqsock.Close()
reqsock.Connect(reqaddy)
reqsock.SetSubscribe("")
repsock, _ = zmq.NewSocket(zmq.REQ)
repsock.Connect(repaddy)
defer repsock.Close()
fmt.Println("[PRIVATE] Connected to PUBLIC")
for subscribed {
fmt.Println("[PRIVATE] Receiving")
r, _ := reqsock.Recv(0)
fmt.Printf("[PRIVATE] Received %d\n", len(r))
fmt.Printf("[PRIVATE] Executing inner HTTP request\n")
req, e := messages.NewRequest(r)
if e != nil {
fmt.Printf("Terrible error trying to recreate request")
panic(e)
}
reply, body, e := MakeRequest(req)
SendReply(reply, body, repsock)
}
fmt.Println("[PRIVATE] Unsubscribing")
}
示例2: main
func main() {
go listener_thread()
time.Sleep(time.Millisecond * 5)
// This is where the weather server sits
frontend, _ := zmq.NewSocket(zmq.XSUB)
defer frontend.Close()
frontend.Bind(proxy_frontend_url_port)
// This is our public endpoint for subscribers
backend, _ := zmq.NewSocket(zmq.XPUB)
defer backend.Close()
backend.Bind(proxy_backend_url_port)
listener, _ := zmq.NewSocket(zmq.PAIR)
listener.Connect("inproc://pipe")
log.Println("0MQ proxy started!")
log.Println("Frontend protocl/url/port:", proxy_frontend_url_port)
log.Println("Backend protocol/url/port:", proxy_backend_url_port)
// Run the proxy until the user interrupts us
err := zmq.Proxy(frontend, backend, listener)
log.Fatalln("Proxy interrupted:", err)
}
示例3: main
func main() {
srv := &clonesrv_t{
port: 5556,
kvmap: make(map[string]*kvmsg.Kvmsg),
}
// Set up our clone server sockets
srv.snapshot, _ = zmq.NewSocket(zmq.ROUTER)
srv.snapshot.Bind(fmt.Sprint("tcp://*:", srv.port))
srv.publisher, _ = zmq.NewSocket(zmq.PUB)
srv.publisher.Bind(fmt.Sprint("tcp://*:", srv.port+1))
srv.collector, _ = zmq.NewSocket(zmq.PULL)
srv.collector.Bind(fmt.Sprint("tcp://*:", srv.port+2))
// Register our handlers with reactor
reactor := zmq.NewReactor()
reactor.AddSocket(srv.snapshot, zmq.POLLIN,
func(e zmq.State) error { return snapshots(srv) })
reactor.AddSocket(srv.collector, zmq.POLLIN,
func(e zmq.State) error { return collector(srv) })
reactor.AddChannelTime(time.Tick(1000*time.Millisecond), 1,
func(v interface{}) error { return flush_ttl(srv) })
log.Println(reactor.Run(100 * time.Millisecond)) // precision: .1 seconds
}
示例4: main
func main() {
file := new(ZMQConfigFile)
fileReader, err := os.Open("config.json")
if err != nil {
log.Panicf("Error: %v", err)
}
jsonReader := json.NewDecoder(fileReader)
err = jsonReader.Decode(&file)
fileReader.Close()
if err != nil {
log.Panicf("Error: %v", err)
}
serverToMe, _ := zmq.NewSocket(zmq.PULL)
defer serverToMe.Close()
applyZMQConfig(serverToMe, file.ServerToMe)
meToLink, _ := zmq.NewSocket(zmq.PUSH)
defer meToLink.Close()
applyZMQConfig(meToLink, file.MeToLink)
linkToMe, _ := zmq.NewSocket(zmq.XSUB)
defer linkToMe.Close()
applyZMQConfig(linkToMe, file.LinkToMe)
meToServer, _ := zmq.NewSocket(zmq.XPUB)
defer meToServer.Close()
applyZMQConfig(meToServer, file.MeToServer)
go zmq.Proxy(serverToMe, meToLink, nil)
zmq.Proxy(linkToMe, meToServer, nil)
}
示例5: New
func New(primary bool, local, remote string) (bstar *Bstar, err error) {
bstar = &Bstar{}
// Initialize the Binary Star
bstar.Reactor = zmq.NewReactor()
if primary {
bstar.state = state_PRIMARY
} else {
bstar.state = state_BACKUP
}
// Create publisher for state going to peer
bstar.statepub, err = zmq.NewSocket(zmq.PUB)
bstar.statepub.Bind(local)
// Create subscriber for state coming from peer
bstar.statesub, err = zmq.NewSocket(zmq.SUB)
bstar.statesub.SetSubscribe("")
bstar.statesub.Connect(remote)
// Set-up basic reactor events
bstar.Reactor.AddChannelTime(time.Tick(bstar_HEARTBEAT), 1,
func(i interface{}) error { return bstar.send_state() })
bstar.Reactor.AddSocket(bstar.statesub, zmq.POLLIN,
func(e zmq.State) error { return bstar.recv_state() })
return
}
示例6: main
func main() {
// Start authentication engine
zmq.AuthSetVerbose(true)
zmq.AuthStart()
zmq.AuthAllow("domain1", "127.0.0.1")
// Tell the authenticator how to handle PLAIN requests
zmq.AuthPlainAdd("domain1", "admin", "secret")
// Create and bind server socket
server, _ := zmq.NewSocket(zmq.PUSH)
server.ServerAuthPlain("domain1")
server.Bind("tcp://*:9000")
// Create and connect client socket
client, _ := zmq.NewSocket(zmq.PULL)
client.SetPlainUsername("admin")
client.SetPlainPassword("secret")
client.Connect("tcp://127.0.0.1:9000")
// Send a single message from server to client
_, err := server.Send("Hello", 0)
checkErr(err)
message, err := client.Recv(0)
checkErr(err)
if message != "Hello" {
log.Fatalln(message, "!= Hello")
}
zmq.AuthStop()
fmt.Println("Woodhouse test OK")
}
示例7: main
func main() {
// Socket to receive messages on
receiver, _ := zmq.NewSocket(zmq.PULL)
defer receiver.Close()
receiver.Bind("tcp://*:5558")
// Socket for worker control
controller, _ := zmq.NewSocket(zmq.PUB)
defer controller.Close()
controller.Bind("tcp://*:5559")
// Wait for start of batch
receiver.Recv(0)
// Start our clock now
start_time := time.Now()
// Process 100 confirmations
for task_nbr := 0; task_nbr < 100; task_nbr++ {
receiver.Recv(0)
if task_nbr%10 == 0 {
fmt.Print(":")
} else {
fmt.Print(".")
}
}
fmt.Println("\nTotal elapsed time:", time.Since(start_time))
// Send kill signal to workers
controller.Send("KILL", 0)
// Finished
time.Sleep(time.Second) // Give 0MQ time to deliver
}
示例8: StartZeromqJsonRouterDealerServer
func StartZeromqJsonRouterDealerServer(port string) {
frontend, _ := zmq.NewSocket(zmq.ROUTER)
defer frontend.Close()
backend, _ := zmq.NewSocket(zmq.DEALER)
defer backend.Close()
frontend.Bind("tcp://0.0.0.0:" + port)
backend.Bind("inproc://backend")
// start num cpu request processors
for i := 0; i < runtime.NumCPU(); i++ {
go func() {
responder, _ := zmq.NewSocket(zmq.REP)
defer responder.Close()
responder.Connect("inproc://backend")
for {
request, _ := responder.RecvBytes(0)
var body Request
json.Unmarshal(request, body)
response, _ := json.Marshal(Response{Method: body.Method, PayloadLength: len(body.Payload)})
responder.Send(string(response), 0)
}
}()
}
err := zmq.Proxy(frontend, backend, nil)
log.Fatalln(err)
}
示例9: main
func main() {
// Connect to task ventilator
receiver, _ := zmq.NewSocket(zmq.PULL)
defer receiver.Close()
receiver.Connect("tcp://localhost:5557")
// Connect to weather server
subscriber, _ := zmq.NewSocket(zmq.SUB)
defer subscriber.Close()
subscriber.Connect("tcp://localhost:5556")
subscriber.SetSubscribe("10001 ")
// Initialize poll set
poller := zmq.NewPoller()
poller.Add(receiver, zmq.POLLIN)
poller.Add(subscriber, zmq.POLLIN)
// Process messages from both sockets
for {
sockets, _ := poller.Poll(-1)
for _, socket := range sockets {
switch s := socket.Socket; s {
case receiver:
task, _ := s.Recv(0)
// Process task
fmt.Println("Got task:", task)
case subscriber:
update, _ := s.Recv(0)
// Process weather update
fmt.Println("Got weather update:", update)
}
}
}
}
示例10: RunForwarderProxy
// see explanation here http://api.zeromq.org/4-0:zmq-proxy#toc2
func RunForwarderProxy(pubPort string, subPort string) {
var err error
glog.V(1).Info("pub port :", pubPort, " sub port :", subPort)
// Socket facing clients
frontend, _ := zmq.NewSocket(zmq.XSUB)
defer frontend.Close()
err = frontend.Bind("tcp://*:" + pubPort)
if err != nil {
glog.Error("Error Binding frontend:", err)
}
// Socket facing services
backend, _ := zmq.NewSocket(zmq.XPUB)
defer backend.Close()
err = backend.Bind("tcp://*:" + subPort)
if err != nil {
glog.Error("Error Binding backend:", err)
}
// Start the proxy
err = zmq.Proxy(frontend, backend, nil)
glog.Error("Proxy interrupted:", err)
}
示例11: TestPing
// Yay! Test function.
func TestPing(t *testing.T) {
// Create pair of sockets we can send through
// Output socket
output, err := zmq.NewSocket(zmq.DEALER)
if err != nil {
t.Fatal(err)
}
defer output.Close()
routingId := "Shout"
output.SetIdentity(routingId)
err = output.Bind("inproc://selftest-ping")
if err != nil {
t.Fatal(err)
}
defer output.Unbind("inproc://selftest-ping")
// Input socket
input, err := zmq.NewSocket(zmq.ROUTER)
if err != nil {
t.Fatal(err)
}
defer input.Close()
err = input.Connect("inproc://selftest-ping")
if err != nil {
t.Fatal(err)
}
defer input.Disconnect("inproc://selftest-ping")
// Create a Ping message and send it through the wire
ping := NewPing()
err = ping.Send(output)
if err != nil {
t.Fatal(err)
}
transit, err := Recv(input)
if err != nil {
t.Fatal(err)
}
tr := transit.(*Ping)
err = tr.Send(input)
if err != nil {
t.Fatal(err)
}
transit, err = Recv(output)
if err != nil {
t.Fatal(err)
}
if routingId != string(tr.RoutingId()) {
t.Fatalf("expected %s, got %s", routingId, string(tr.RoutingId()))
}
}
示例12: main
func main() {
// Socket to receive messages on
receiver, _ := zmq.NewSocket(zmq.PULL)
defer receiver.Close()
receiver.Connect("tcp://localhost:5557")
// Socket to send messages to
sender, _ := zmq.NewSocket(zmq.PUSH)
defer sender.Close()
sender.Connect("tcp://localhost:5558")
// Process tasks forever
for {
s, _ := receiver.Recv(0)
// Simple progress indicator for the viewer
fmt.Print(s + ".")
// Do the work
msec, _ := strconv.Atoi(s)
time.Sleep(time.Duration(msec) * time.Millisecond)
// Send results to sink
sender.Send("", 0)
}
}
示例13: ZmqPubSubProxy
// ZmqPubSubProxy Implements a many-to-many device on a zmq PUB-SUB connection
func ZmqPubSubProxy(host string, portIn int, portOut int, logger *log.Logger) {
xsub, _ := zmq.NewSocket(zmq.SUB)
xpub, _ := zmq.NewSocket(zmq.PUB)
defer xsub.Close()
defer xpub.Close()
addrIn := fmt.Sprintf("tcp://*:%d", portIn)
addrOut := fmt.Sprintf("tcp://*:%d", portOut)
logger.Println("ZMQ XSUB on", addrIn)
xsub.Bind(addrIn)
xsub.SetSubscribe("")
logger.Println("ZMQ XPUB on", addrOut)
xpub.Bind(addrOut)
poller := zmq.NewPoller()
poller.Add(xsub, zmq.POLLIN)
for {
// keep looping
sockets, _ := poller.Poll(5 * time.Second)
for _, socket := range sockets {
switch s := socket.Socket; s {
case xsub:
ZmqSendMulti(xpub, ZmqRecvMulti(s))
}
}
}
}
示例14: router
func router(log func(level int, format string, a ...interface{})) {
// inproc socket for receiving requests from frontend
frontend, error := zmq.NewSocket(zmq.ROUTER)
if error != nil {
log(3, "error creating frontend socket: %s\n", error)
} else {
defer frontend.Close()
log(0, "created frontend socket\n")
}
error = frontend.Bind("ipc:///tmp/feeds/upstream")
if error != nil {
log(3, "error binding [ipc:///tmp/feeds/upstream] frontend socket: %s\n", error)
} else {
log(0, "bound frontend socket to [ipc:///tmp/feeds/upstream]\n")
}
// inproc socket for sending requests to downstream
backend, error := zmq.NewSocket(zmq.DEALER)
if error != nil {
log(3, "error creating backend socket: %s\n", error)
} else {
defer backend.Close()
log(0, "created backend socket\n")
}
error = backend.Bind("ipc:///tmp/feeds/downstream")
if error != nil {
log(3, "error binding [ipc:///tmp/feeds/downstream] backend socket: %s\n", error)
} else {
log(0, "bound backend socket to [ipc:///tmp/feeds/downstream]\n")
}
// Connect backend to frontend via a proxy
err := zmq.Proxy(frontend, backend, nil)
log(0, "Proxy interrupted: %s\n", err)
}
示例15: 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)}
}