在两个不同的程序之间发送/接收数据

时间:2013-12-30 12:50:29

标签: c++ python sockets

我主要在这里寻找一些建议。

我正在开发一个应用程序,主要处理(存储在服务器上)在C ++中执行,GUI(前端)在Python中执行。这两个程序将相互通信。 Python将发送C ++程序所需的文件,并为C ++程序提供一些数据。然后,后端将与处理过的数据进行通信。

因此使用套接字会更好吗?我考虑过使用文本文件完成此操作,但是,已经没有这个想法,而只是将数据保存为.txt文件,以便在将来的实例中打开它。另外,如果我要使用套接字,使用Python / C ++会有任何冲突吗?

非常感谢任何帮助或建议。

4 个答案:

答案 0 :(得分:4)

尝试ZeroMQ

  

ØMQ(也称为ZeroMQ,0MQ或zmq)看起来像一个嵌入式   网络库,但就像一个并发框架。它给你   在各种传输中携带原子消息的套接字   进程内,进程间,TCP和多播。您可以连接套接字   N-to-N具有扇出,发布子,任务分配等模式   请求 - 应答。它足够快,可以成为集群的结构   产品。其异步I / O模型为您提供可扩展的多核   应用程序,构建为异步消息处理任务。它有一个   语言API的得分,并在大多数操作系统上运行。 ØMQ来自   iMatix和LGPLv3开源。

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)

答案 1 :(得分:0)

我会选择命名管道,在您的环境中随时可用,因为它类似于读取和写入文件,但它也具有类似于套接字的功能,即您可以使它们在网络上通信(不同的主机)

答案 2 :(得分:0)

Would therefore it be better to use Sockets?

在网络上工作时,您将始终使用套接字。我们可以说套接字是每个网络应用程序的核心。这样说,在回答你的问题时,我认为你的应用程序非常简单(正如你所描述的那样)所以最好不要使用某些第三方模块甚至整个框架来实现这一点。

查看此答案Python - Sending files over sockets 这到c c send and receive file

我希望能帮到你。

答案 3 :(得分:-1)

Python基于C ++,就像改进一样。

如果要在一台计算机上的这些应用程序之间发送,可以使用文件映射。 http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx Imo是如何做到这一点的最好方法。

但是,如果你想在两台计算机之间发送它,请使用TCP套接字

相关问题