欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pyzmq的4种模式(PAIR)笔记 博客分类: python pythonzmq

程序员文章站 2024-02-23 12:03:22
...

    今天学习下pyzmq,感觉怎么样呢,看了官网开头,记录之,基本上也可以算个翻译

     Exclusive pair pattern 特点

           1. 双向通讯

           2. 套接字无状态(封装的很好吧)

           3. 只能有一个对等连接(这能干嘛用,似乎没啥用)

           4. 服务端监听,客户端连接

pyzmq的4种模式(PAIR)笔记
            
    
    博客分类: python pythonzmq

然后:你根本不用考虑message接收的完整不完整,你照做就是了!(原文)

官方example在此:

pairserver.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind("tcp://*:%s" % port)
while True:
    socket.send("Server message to client3")
    msg = socket.recv()
    print msg
    time.sleep(1)

pairclient.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:%s" % port)
while True:
    msg = socket.recv()
    print msg
    socket.send("client message to server1")
    socket.send("client message to server2")
    time.sleep(1)

 

然后run起来,有点小问题,client连续send了2次,server倒是没问题,来一个响应一个,client的recv()不是应该收2个 "Server message to client3"吗

 改一下server:

import zmq
import time

port = '5556'
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind('tcp://*:%s'%port)
i = 0
while True:
	i += 1
	print 'begin:',i
	socket.send('msg from server:'+str(i))
	msg = socket.recv()
	print 'msg:%s'%msg
	time.sleep(1)

 run起来:

client: 

begin
msg from server:1
begin
msg from server:2
begin
msg from server:3

 server:

begin: 1
msg:client msg to server -1
begin: 2
msg:client msg to server -2
begin: 3
msg:client msg to server -1
begin: 4
msg:client msg to server -2
begin: 5
msg:client msg to server -1
begin: 6

 好吧,它确实没丢任何message,只能说呵呵,这封装的,有点别扭。

相关标签: python zmq