本文整理汇总了Golang中github.com/alecthomas/gozmq.NewContext函数的典型用法代码示例。如果您正苦于以下问题:Golang NewContext函数的具体用法?Golang NewContext怎么用?Golang NewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewContext函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
arg := "server"
if len(os.Args) > 1 {
arg = os.Args[1]
}
log.Info("=[%s\n]===================================================================", arg)
path := os.Getenv("GOPATH")
fmt.Println(path)
path = os.Getenv("GOROOT")
fmt.Println(path)
syscall_path, ok := syscall.Getenv("_system_arch")
fmt.Println(syscall_path)
fmt.Println(ok)
path = os.Getenv("_system_name")
fmt.Println(path)
if arg == "server" || arg == "" {
log.Info("run server!")
context, _ := zmq.NewContext()
socket, _ := context.NewSocket(zmq.REP)
socket.Bind("tcp://127.0.0.1:5000")
socket.Bind("tcp://127.0.0.1:6000")
for {
msg, _ := socket.Recv(0)
println("Got", string(msg))
socket.Send(msg, 0)
}
} else if arg == "client" {
log.Info("client server!")
context, _ := zmq.NewContext()
socket, _ := context.NewSocket(zmq.REQ)
socket.Connect("tcp://127.0.0.1:5000")
socket.Connect("tcp://127.0.0.1:6000")
for i := 0; i < 10; i++ {
msg := fmt.Sprintf("msg %d", i)
socket.Send([]byte(msg), 0)
println("Sending", msg)
socket.Recv(0)
}
}
}
示例2: main
func main() {
// Initialize publisher
pub := entity.Publisher{}
pub.AppendAddress("tcp://*:6602")
context, _ := zmq.NewContext()
defer context.Close()
if err := pub.InitialBinding(context); err != nil {
log.Fatalln("Initialize publisher failure.", err)
}
value := example.Test{}
value.Label = proto.String("value1")
value.Type = proto.Int32(0)
for {
time.Sleep(time.Second)
*value.Type = value.GetType() + 2
if err := pub.Write(&value); err != nil {
log.Println("Publish value failure.")
} else {
log.Println("Publish value okay.")
}
}
}
示例3: main
func main() {
file, err := ioutil.ReadFile("./config.json")
if err != nil {
fmt.Printf("File error: %v\n", err)
os.Exit(1)
}
fmt.Printf("%s\n", file)
config := SensuConfig{}
json.Unmarshal(file, &config)
fmt.Printf("Config: %v\n", config)
context, _ := zmq.NewContext()
socket, _ := context.NewSocket(zmq.REQ)
for _, server := range config.Servers {
uri := fmt.Sprintf("tcp://%s:%d", server.Host, server.Port)
fmt.Printf("Connecting to server: %s\n", uri)
socket.Connect(uri)
}
cmd := exec.Command("echo", "-n", "foo")
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("Command error: %v\n", err)
}
cmd.Wait()
fmt.Printf("Command output: %s\n", output)
}
示例4: main
func main() {
context, _ := zmq.NewContext()
socket, _ := context.NewSocket(zmq.PUB)
defer context.Close()
defer socket.Close()
socket.Bind("tcp://*:5556")
socket.Bind("ipc://weather.ipc")
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// loop for a while aparently
for {
// make values that will fool the boss
zipcode := rand.Intn(100000)
temperature := rand.Intn(215) - 80
relhumidity := rand.Intn(50) + 10
msg := fmt.Sprintf("%d %d %d", zipcode, temperature, relhumidity)
// Send message to all subscribers
socket.Send([]byte(msg), 0)
}
}
示例5: client_task
func client_task(c chan string) {
context, _ := zmq.NewContext()
client, _ := context.NewSocket(zmq.DEALER)
defer context.Close()
defer client.Close()
client.SetIdentity("C")
client.Connect("tcp://localhost:5555")
fmt.Println("Setting up test...")
time.Sleep(time.Duration(100) * time.Millisecond)
fmt.Println("Synchronous round-trip test...")
start := time.Now()
requests := 10000
for i := 0; i < requests; i++ {
client.Send([]byte("hello"), 0)
client.Recv(0)
}
fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))
fmt.Println("Asynchronous round-trip test...")
start = time.Now()
for i := 0; i < requests; i++ {
client.Send([]byte("hello"), 0)
}
for i := 0; i < requests; i++ {
client.Recv(0)
}
fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))
c <- "done"
}
示例6: createSockets
// createSockets initializes the sockets for the socket group based on values from zmq.
func createSockets() (*zmq.Context, SocketGroup, error) {
context, err := zmq.NewContext()
if err != nil {
return context, SocketGroup{}, errors.Wrap(err, "Could not create zmq Context")
}
var sg SocketGroup
sg.ShellSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Shell Socket")
}
sg.ControlSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Control Socket")
}
sg.StdinSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Stdin Socket")
}
sg.IOPubSocket, err = context.NewSocket(zmq.PUB)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get IOPub Socket")
}
return context, sg, nil
}
示例7: Startmaster
func Startmaster(data Interfacemaster) {
var queries_file = flag.String("q", "", "queries file")
var index_file = flag.String("i", "", "index file")
flag.Parse()
// ventilator
context, _ := zmq.NewContext()
defer context.Close()
sender, _ := context.NewSocket(zmq.PUSH)
defer sender.Close()
sender.Bind("tcp://*:5557")
fmt.Println("Sending tasks to workers...")
//Sink
receiver, _ := context.NewSocket(zmq.PULL)
defer receiver.Close()
receiver.Bind("tcp://*:5558")
vent_quit := make(chan int)
if *queries_file != "" && *index_file != "" {
f, err := os.Open(*queries_file)
if err != nil {
panic("error opening file " + *queries_file)
}
r := bufio.NewReader(f)
go func() {
count := 0
for {
line, err := r.ReadBytes('\n')
if err != nil {
break
}
if len(line) > 1 {
msg := data.ProduceMsg(line, count, *index_file)
sender.Send(msg, 0)
}
count++
}
vent_quit <- count
}()
}
read_count := 0
result_count := 0
// receving results from workers
for result_count < read_count || read_count <= 0 {
select {
case read_count = <-vent_quit:
break
default:
break
}
msgbytes, _ := receiver.Recv(0)
result_count++
data.AnalyzeResult(msgbytes)
}
}
示例8: newBroker
func newBroker(endpoint string, heartbeatIntv, workerExpiry time.Duration) (broker Broker, err error) {
context, err := zmq.NewContext()
if err != nil {
return
}
socket, err := context.NewSocket(zmq.ROUTER)
if err != nil {
return
}
err = socket.SetSockOptInt(zmq.LINGER, 0)
if err != nil {
return
}
err = socket.Bind(endpoint)
if err != nil {
return
}
broker = &mdBroker{
context: context,
services: make(map[string]*mdService),
socket: socket,
waiting: NewList(),
workers: make(map[string]*refWorker),
heartbeatAt: time.Now().Add(heartbeatIntv),
heartbeatIntv: heartbeatIntv,
workerExpiry: workerExpiry,
errors: make(chan error),
}
return
}
示例9: main
func main() {
context, _ := zmq.NewContext()
defer context.Close()
// Connect our subscriber socket
subscriber, _ := context.NewSocket(zmq.SUB)
defer subscriber.Close()
subscriber.SetSockOptString(zmq.IDENTITY, "Hello")
subscriber.SetSockOptString(zmq.SUBSCRIBE, "")
subscriber.Connect("tcp://localhost:5565")
// Synchronize with publisher
sync, _ := context.NewSocket(zmq.PUSH)
defer sync.Close()
sync.Connect("tcp://localhost:5564")
sync.Send([]byte{}, 0)
// Get updates, expect random Ctrl-C death
for {
data, _ := subscriber.Recv(0)
str := string(data)
println(str)
if str == "END" {
break
}
}
}
示例10: bindingPub
func bindingPub(addr Address, t *testing.T) {
inst := Publisher{}
inst.Addr = make([]Address, 1)
inst.Addr[0] = addr
err := make(chan error)
context, _ := zmq.NewContext()
defer context.Close()
// select {
// case err <- inst.InitialBinding(context):
// if err != nil {
// t.Errorf("Address should bind on %s, while return %s",
// string(inst.Addr[0]), err)
// }
// case <-time.After(time.Second):
// return
// }
if err <- inst.InitialBinding(context); err != nil {
t.Errorf("Address should bind on %s, while return %s\n",
string(inst.Addr[0]), <-err)
}
}
示例11: main
func main() {
context, _ := zmq.NewContext()
defer context.Close()
// Socket to talk to clients
publisher, _ := context.NewSocket(zmq.PUB)
defer publisher.Close()
publisher.Bind("tcp://*:5561")
// Socket to receive signals
syncservice, _ := context.NewSocket(zmq.REP)
defer syncservice.Close()
syncservice.Bind("tcp://*:5562")
// Get synchronization from subscribers
for i := 0; i < subsExpected; i = i + 1 {
syncservice.Recv(0)
syncservice.Send([]byte(""), 0)
}
for update_nbr := 0; update_nbr < 1000000; update_nbr = update_nbr + 1 {
publisher.Send([]byte("Rhubarb"), 0)
}
publisher.Send([]byte("END"), 0)
}
示例12: runZmqStream
func runZmqStream() {
var context zmq.Context
var socket zmq.Socket
// connect to zmq
var err error
if context, err = zmq.NewContext(); err != nil {
panic("No ZMQ Context?")
}
defer context.Close()
if socket, err = context.NewSocket(zmq.SUB); err != nil {
panic("No ZMQ Socket Outbound??")
}
defer socket.Close()
socket.Connect("tcp://localhost:5558")
socket.SetSockOptString(zmq.SUBSCRIBE, "")
for {
// block here, waiting for inbound requests
msg, _ := socket.Recv(0)
if len(msg) > 0 {
parts := strings.Split(string(msg), "\n\n")
process(parts[0])
}
}
}
示例13: main
func main() {
context, _ := zmq.NewContext()
publisher, _ := context.NewSocket(zmq.PUB)
defer publisher.Close()
publisher.Bind(chatroom.PUBLISHER_ADDRESS)
router, _ := context.NewSocket(zmq.PULL)
defer router.Close()
router.Bind(chatroom.POST_ADDRESS)
stat_channel := make(chan int)
go admin_server(stat_channel)
receiver_channel := bind_to_channel(router)
for {
select {
case msg := <-receiver_channel:
go func() {
stat_channel <- 1
publisher.Send(msg, 0)
}()
}
}
}
示例14: main
func main() {
context, _ := zmq.NewContext()
defer context.Close()
client, _ := context.NewSocket(zmq.ROUTER)
defer client.Close()
client.Bind("ipc://routing.ipc")
rand.Seed(time.Now().Unix())
for i := 0; i < NBR_WORKERS; i++ {
go workerTask()
}
for i := 0; i < NBR_WORKERS*10; i++ {
// LRU worker is next waiting in queue
parts, err := client.RecvMultipart(0)
if err != nil {
print(err)
}
address := parts[0]
client.SendMultipart([][]byte{address, []byte(""), []byte("This is the workload")}, 0)
}
// Now ask mamas to shut down and report their results
for i := 0; i < NBR_WORKERS; i++ {
parts, err := client.RecvMultipart(0)
if err != nil {
print(err)
}
address := parts[0]
client.SendMultipart([][]byte{address, []byte(""), []byte("END")}, 0)
}
}
示例15: workerTask
func workerTask() {
context, _ := zmq.NewContext()
defer context.Close()
worker, _ := context.NewSocket(zmq.REQ)
worker.SetSockOptString(zmq.IDENTITY, randomString())
worker.Connect("ipc://routing.ipc")
defer worker.Close()
var total int
for {
err := worker.Send([]byte("ready"), 0)
if err != nil {
print(err)
}
data, _ := worker.Recv(0)
if string(data) == "END" {
id, _ := worker.GetSockOptString(zmq.IDENTITY)
fmt.Printf("Processed: %2d tasks (%s)\n", total, id)
break
}
total += 1
msec := rand.Intn(1000)
time.Sleep(time.Duration(msec) * time.Millisecond)
}
}