使用PAIR/PAIR
模式,我希望客户端发送一些消息,接收服务器显示收到的消息。我有一个客户端通过python代码发送:
import zmq
import time
context = zmq.Context()
port = "5555"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:%s" % port)
m=""
while m!="eof":
m=input(">")
socket.send_string(m)
和一个swift GUI应用程序的服务器,使用SwiftyZeroMQ库,在文本视图中显示收到的文本,片段:
import Cocoa
import SwiftyZeroMQ
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var alert_txt: NSTextView!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
do {
self.alert_txt.string="wait..."
let endpoint = "tcp://*:5555"
let textToBeSent = "swift: get"
let context = try SwiftyZeroMQ.Context()
let receiver = try context.socket(.pair)
try receiver.bind(endpoint)
let poller = SwiftyZeroMQ.Poller()
try poller.register(socket: receiver, flags: .pollIn)
var sdct=true
while sdct{
let socks = try poller.poll(timeout: 1000)
for subscriber in socks.keys {
if socks[subscriber] == SwiftyZeroMQ.PollFlags.pollIn {
let text = try subscriber.recv(options: .dontWait)
print("received '\(text)'")
self.alert_txt.string+=text!
if text=="eof"
{
sdct=false
}
}
}
}
} catch {
print(error)
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
然而,swift GUI显示旋转沙滩球,文本字段直到" eof"收到了; print("received '\(text)'")
有效,我可以在xcode控制台输出中看到它更新。我认为涉及poller
的代码存在问题,但我无法解决问题。在这个PAIR/PAIR
模式下,我使用python接收端的测试代码按预期工作:
import time
import zmq
context = zmq.Context()
port = "5555"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind("tcp://*:%s" % port)
msg=""
while msg !="eof":
msg = socket.recv()
msg=msg.decode("utf-8")
print(msg,"\n=========")
答案 0 :(得分:0)
实际上,您的applicationDidFinishLaunching
直到收到“ eof”信息后才返回,因此macOS认为您的应用已停止运行-因此是抢滩。
尝试将while sdct { ... }
移到一个单独的函数中,然后在后台线程上调用它。安排最终的UI更新在主线程上进行。