我主要在这里寻找一些建议。
我正在开发一个应用程序,其中主要处理(存储在服务器上)是用 C++ 执行的,GUI(前端)是用 Python 执行的。这两个程序将相互通信。 Python 将发送 C++ 程序运行所需的文件,并为 C++ 程序提供一些数据以供处理。后端随后将与处理后的数据进行通信。
因此使用套接字会更好吗?我想过使用文本文件来完成这个,但是,已经放弃了这个想法,而是将数据保存为 .txt 文件,以便将来可以打开它。另外,如果我要使用套接字,使用 Python/C++ 会不会有任何冲突?
最佳答案
尝试 ZeroMQ
ØMQ (also known as ZeroMQ, 0MQ, or zmq) looks like an embeddable networking library but acts like a concurrency framework. It gives you sockets that carry atomic messages across various transports like in-process, inter-process, TCP, and multicast. You can connect sockets N-to-N with patterns like fan-out, pub-sub, task distribution, and request-reply. It's fast enough to be the fabric for clustered products. Its asynchronous I/O model gives you scalable multicore applications, built as asynchronous message-processing tasks. It has a score of language APIs and runs on most operating systems. ØMQ is from iMatix and is LGPLv3 open source.
C++ Hello World 服务器:
//
// Hello World server in C++
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h>
#endif
int main () {
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REP);
socket.bind ("tcp://*:5555");
while (true) {
zmq::message_t request;
// Wait for next request from client
socket.recv (&request);
std::cout << "Received Hello" << std::endl;
// Do some 'work'
#ifndef _WIN32
sleep(1);
#else
Sleep (1);
#endif
// Send reply back to client
zmq::message_t reply (5);
memcpy ((void *) reply.data (), "World", 5);
socket.send (reply);
}
return 0;
}
Python 客户端:
#
# Hello World client in Python
# Connects REQ socket to tcp://localhost:5555
# Sends "Hello" to server, expects "World" back
#
import zmq
context = zmq.Context()
# Socket to talk to server
print "Connecting to hello world server…"
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
# Do 10 requests, waiting each time for a response
for request in range(10):
print "Sending request %s …" % request
socket.send("Hello")
# Get the reply.
message = socket.recv()
print "Received reply %s [ %s ]" % (request, message)
关于c++ - 在两个不同的程序之间发送/接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839944/