我正在尝试使用ZeroMQ Request-Reply Pattern在Python和Scala之间实现请求-响应示例。基于ZMQ文档提供的代码,我成功地在Scala中运行了请求者并在Python中运行了服务器。
从scala到python: rrclient scala 和 rrserver python 现在我想做相反的事情。一个Python请求者和一个Scala回复者。
从python到scala: rrclient python 和 rrserver scala 这是Python客户端代码。
我已经尝试从Python发送简单字符串和0结尾的字符串,但都没有成功。
在Python中发送:
我做错了什么?我觉得这与Python字符串有关,但我还没有解决它。
从scala到python: rrclient scala 和 rrserver python 现在我想做相反的事情。一个Python请求者和一个Scala回复者。
从python到scala: rrclient python 和 rrserver scala 这是Python客户端代码。
import zmq
# Prepare our context and sockets
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5559")
# Do 10 requests, waiting each time for a response
for request in range(1,11):
socket.send(b"Hello")
message = socket.recv()
print("Received reply %s [%s]" % (request, message))
这里是Scala代码
import org.zeromq.ZMQ
import org.zeromq.ZMQ.{Context,Socket}
object rrserver {
def main(args : Array[String]) {
// Prepare our context and socket
val context = ZMQ.context(1)
val receiver = context.socket(ZMQ.REP)
receiver.connect("tcp://localhost:5559")
while (true) {
// Wait for next request from client
// We will wait for a 0-terminated string (C string) from the client,
// so that this server also works with The Guide's C and C++ "Hello World" clients
//IT BLOCKS HERE
val request = receiver.recv (0)
println(request)
// In order to display the 0-terminated string as a String,
// we omit the last byte from request
// println ("Received request: [" + new String(request,0,request.length-1)
// Creates a String from request, minus the last byte
// + "]")
// Do some 'work'
// try {
// Thread.sleep (1000)
// } catch {
// case e: InterruptedException => e.printStackTrace()
// }
// Send reply back to client
// We will send a 0-terminated string (C string) back to the client,
// so that this server also works with The Guide's C and C++ "Hello World" clients
// val reply = "World ".getBytes
// reply(reply.length-1)=0 //Sets the last byte of the reply to 0
// receiver.send(reply, 0)
}
}
}
在Scala示例中,它要求以0结尾的字符串作为c字符串。我已经尝试从Python发送简单字符串和0结尾的字符串,但都没有成功。
在Python中发送:
socket.send(b"Hello")
//or
socket.send(b"hello\x00")
在Scala中接收:
//result is always null here
val request = receiver.recv (0)
我做错了什么?我觉得这与Python字符串有关,但我还没有解决它。