我试图让Scala程序通过zeromq使用请求 - 回复模式与c ++程序进行通信。 scala程序应该向回复的C ++程序发送请求。
但是我看到了错误
org.zeromq.ZMQException:无法在当前状态下完成操作
但我在文件中找到的只是在发送第二个请求之前必须阅读回复。在我的情况下,我发出一个请求,然后读取响应(这是抛出异常的地方)。
服务器代码:
#include "zmq.hpp"
#include <string>
#include <iostream>
#include <thread>
int main()
{
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
socket.bind("tcp://*:5555");
while (1) {
zmq::message_t request;
socket.recv(&request);
std::string requ = std::string(static_cast<char*>(request.data()), request.size());
std::cout << requ << std::endl;
// Write response
zmq::message_t req(2);
memcpy((void *)req.data(), "ok", 5);
socket.send(req);
}
}
客户代码:
import org.zeromq.ZMQ
import org.zeromq.ZMQ.{Context, Socket}
object Adapter {
def main( args: Array[String] ) = {
val context = ZMQ.context(1)
val socket = context.socket(ZMQ.REQ)
println { "Connecting to backend" }
socket.connect("tcp://127.0.0.1:5555")
val request = "1 1 1 1".getBytes()
request(request.length - 1) = 0.toByte
println { "Sending Request" }
if (!socket.send(request, 0))
println{ "could not send"}
println { "Receiving Response" }
val reply = socket.recv(0)
println { "Received reply: " + new String(reply, 0, reply.length - 1) }
}
}
sbt的完整输出:
OpenJDK 64-Bit Server VM warning: You have loaded library /tmp/jna7980154308052950568.tmp which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
Connecting to backend
Sending Request
Receiving Response
[error] (run-main-0) org.zeromq.ZMQException: Operation cannot be accomplished in current state
org.zeromq.ZMQException: Operation cannot be accomplished in current state
at org.zeromq.ZMQ$Socket.raiseZMQException(ZMQ.java:448)
at org.zeromq.ZMQ$Socket.recv(ZMQ.java:368)
at ZeroMQActor$.main(ZeroMQExample.scala:56)
at ZeroMQActor.main(ZeroMQExample.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
[trace] Stack trace suppressed: run last compile:run for the full output.
java.lang.RuntimeException: Nonzero exit code: 1
at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) Nonzero exit code: 1
[error] Total time: 5 s, completed Jun 16, 2015 4:42:42 PM
Sbt拉Scala 2.9.1和akka-zeromq 2.0。我从源代码安装了zeromq 3.5,但是当我安装ubuntu软件包libzqm3-dev时,我看到了相同的行为。一种可能的解决方法是使用JeroMQ,一个纯粹的基于java的zmq实现,但我更愿意依赖于整个堆栈中的一个zmq库,而不是处理互操作问题。
提前致谢。
答案 0 :(得分:0)
我相信
memcpy((void *)req.data(), "ok", 5);
应该是
memcpy((void *)req.data(), "ok", 2);
......这足以打破消息处理。