• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang gozmq.NewContext函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/alecthomas/gozmq.NewContext函数的典型用法代码示例。如果您正苦于以下问题:Golang NewContext函数的具体用法?Golang NewContext怎么用?Golang NewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewContext函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
		}
	}

}
开发者ID:doohee323,项目名称:buildGoInChroot,代码行数:48,代码来源:hello.go


示例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.")
		}
	}

}
开发者ID:ZhangzheBJUT,项目名称:notify,代码行数:28,代码来源:pub.go


示例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)
}
开发者ID:portertech,项目名称:sensu-go,代码行数:29,代码来源:client.go


示例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)
	}
}
开发者ID:Boshin,项目名称:zguide,代码行数:25,代码来源:wuserver.go


示例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"
}
开发者ID:Boshin,项目名称:zguide,代码行数:33,代码来源:tripping.go


示例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
}
开发者ID:gopherds,项目名称:gophernotes,代码行数:31,代码来源:gophernotes.go


示例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)
	}
}
开发者ID:CoralGao,项目名称:DistSys,代码行数:60,代码来源:master.go


示例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
}
开发者ID:varstr,项目名称:majordomo,代码行数:30,代码来源:broker.go


示例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
		}
	}
}
开发者ID:nivertech,项目名称:zguide,代码行数:27,代码来源:durasub.go


示例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)
	}

}
开发者ID:ZhangzheBJUT,项目名称:notify,代码行数:25,代码来源:pub_test.go


示例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)
}
开发者ID:Jay-Krish,项目名称:zguide,代码行数:26,代码来源:syncpub.go


示例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])
		}
	}
}
开发者ID:araddon,项目名称:sentiment,代码行数:27,代码来源:main.go


示例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)
			}()
		}
	}
}
开发者ID:victorhsieh,项目名称:go-chatroom,代码行数:25,代码来源:server.go


示例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)
	}
}
开发者ID:namitkewat,项目名称:zguide,代码行数:34,代码来源:rtreq.go


示例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)
	}
}
开发者ID:namitkewat,项目名称:zguide,代码行数:28,代码来源:rtreq.go


示例16: main

func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	//  Socket to receive messages on
	receiver, _ := context.NewSocket(zmq.PULL)
	defer receiver.Close()
	receiver.Connect("tcp://localhost:5557")

	//  Socket to send messages to task sink
	sender, _ := context.NewSocket(zmq.PUSH)
	defer sender.Close()
	sender.Connect("tcp://localhost:5558")

	//  Process tasks forever
	for {
		msgbytes, _ := receiver.Recv(0)
		fmt.Printf("%s.\n", string(msgbytes))

		//  Do the work
		msec, _ := strconv.ParseInt(string(msgbytes), 10, 64)
		time.Sleep(time.Duration(msec) * 1e6)

		//  Send results to sink
		sender.Send([]byte(""), 0)

	}
}
开发者ID:Boshin,项目名称:zguide,代码行数:28,代码来源:taskwork.go


示例17: main

func main() {

	flag.Parse()
	// set the logger and log level
	SetLogger(log.New(os.Stdout, "", log.Ltime|log.Lshortfile), *logLevel)

	// make a go channel for msgs
	stream := make(chan []byte, 200)
	done := make(chan bool)

	// the stream listener effectively operates in one "thread"
	client := NewBasicAuthClient(*user, *pwd, func(line []byte) {
		stream <- line
	})

	go func() {
		_ = client.Sample(done)

		context, _ := zmq.NewContext()
		socket, _ := context.NewSocket(zmq.PUB) // PUSH?
		socket.Bind(*sink)
		defer func() {
			context.Close()
			socket.Close()
		}()
		for {
			evt := <-stream
			socket.Send(evt, 0)
		}
	}()

	_ = <-done

}
开发者ID:pvulgaris,项目名称:httpstream,代码行数:34,代码来源:zmq.go


示例18: RunAnnouncer

// Handles the setup of the various variables, and the startup of the
// main relay loop.
func RunAnnouncer() {

	context, zmqContextError := gozmq.NewContext()
	if zmqContextError != nil {
		errorHandler("zmqContextError:", zmqContextError.Error())
	}

	listener, listenSocketError := context.NewSocket(gozmq.SUB)
	if listenSocketError != nil {
		errorHandler("listenSocketError", listenSocketError.Error())
	}

	// This ZeroMQ socket is what we receive incoming messages on.
	listener.SetSockOptString(gozmq.SUBSCRIBE, "")

	listener.Bind("tcp://0.0.0.0:8049")

	// This ZeroMQ socket is where we relay the messages back out over.
	sender, senderSocketError := context.NewSocket(gozmq.PUB)
	if senderSocketError != nil {
		errorHandler("senderSocketError", senderSocketError.Error())
	}

	sender.Bind("tcp://0.0.0.0:8050")

	// Let's get this party started.
	announcerLoop(listener, sender)
}
开发者ID:gtaylor,项目名称:emdr-announcer-go,代码行数:30,代码来源:announcer.go


示例19: main

func main() {
	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.SUB)
	defer context.Close()
	defer socket.Close()

	var temps []string
	var err error
	var temp int64
	total_temp := 0
	filter := "59937"

	// find zipcode
	if len(os.Args) > 1 { // ./wuclient 85678
		filter = string(os.Args[1])
	}

	//  Subscribe to just one zipcode (whitefish MT 59937)
	fmt.Printf("Collecting updates from weather server for %s…\n", filter)
	socket.SetSubscribe(filter)
	socket.Connect("tcp://localhost:5556")

	for i := 0; i < 101; i++ {
		// found temperature point
		datapt, _ := socket.Recv(0)
		temps = strings.Split(string(datapt), " ")
		temp, err = strconv.ParseInt(temps[1], 10, 64)
		if err == nil {
			// Invalid string
			total_temp += int(temp)
		}
	}

	fmt.Printf("Average temperature for zipcode %s was %dF \n\n", filter, total_temp/100)
}
开发者ID:Boshin,项目名称:zguide,代码行数:35,代码来源:wuclient.go


示例20: worker_task

func worker_task() {
	context, _ := zmq.NewContext()
	defer context.Close()

	worker, _ := context.NewSocket(zmq.DEALER)
	defer worker.Close()
	worker.SetIdentity(randomString())
	worker.Connect("tcp://localhost:5671")

	total := 0
	for {
		//  Tell the broker we're ready for work
		worker.SendMultipart([][]byte{[]byte(""), []byte("Hi Boss")}, 0)

		//  Get workload from broker, until finished
		parts, _ := worker.RecvMultipart(0)
		workload := parts[1]
		if string(workload) == "Fired!" {
			id, _ := worker.Identity()
			fmt.Printf("Completed: %d tasks (%s)\n", total, id)
			break
		}
		total++

		//  Do some random work
		time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
	}
}
开发者ID:Boshin,项目名称:zguide,代码行数:28,代码来源:rtdealer.go



注:本文中的github.com/alecthomas/gozmq.NewContext函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang gozmq.Poll函数代码示例发布时间:2022-05-24
下一篇:
Golang assert.True函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap