1

我正在尝试通过套接字将数据从 C 程序发送到 python 脚本,以便使用 matplotlib 执行数据的实时可视化。我还使用 wxPython 创建了一个 GUI。我用过socket模块、SocketServer模块和twisted。在每一个中,我都有不同的问题。

使用套接字模块,我收到了不止一条消息。我减少了 recv() 函数的缓冲区大小,但我只得到一个包,之后什么也没有。

然后我开始使用twisted。我仍然将这些包裹作为一个集合而不是一个一个地收集。此外,当在 C 文件中插入延迟时,我的 python 脚本崩溃了。

然后我搬到了 SocketServer 并创建了一个线程来运行服务器。消息如我所愿,但我无法再与 GUI 交互。

我想要做的就是向 Python 脚本发送一串 4 个值,剥离它并绘制它,拥有一个交互式 UI,但我找不到服务器、matplotlib 和 wxPython 协作的示例。

这是我找到并正在使用的 C 代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#define PORT        9992
#define HOST        "localhost"
#define DIRSIZE     8192

main(argc, argv)
int argc; char **argv;
{
char hostname[100];
char dir[DIRSIZE];
int sd;
struct sockaddr_in sin;
struct sockaddr_in pin;
struct hostent *hp;
char message[50];
int i = 0;
int count = 50;

strcpy(hostname,HOST);
if (argc>2)
{ strcpy(hostname,argv[2]); }

/* go find out about the desired host machine */
if ((hp = gethostbyname(hostname)) == 0) {
    perror("gethostbyname");
    exit(1);
}

/* fill in the socket structure with host information */
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(PORT);

/* grab an Internet domain socket */
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
}

/* connect to PORT on HOST */
if (connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) == -1) {
    perror("connect");
    exit(1);
}

/* send a message to the server PORT on machine HOST */
while (i < 100){
    sprintf(message, "%d %d %d %d \n", count, count + 50, count + 100, count + 130);
    if (send(sd, message, strlen(message), 0) == -1) {
        perror("send");
        exit(1);
    }
    count = count + 50;
    i++;
    sleep(1);
}


shutdown (sd, 2);
}

这是我目前拥有的 Python 代码(在网上搜索后):

class ThreadedEchoRequestHandler(SocketServer.StreamRequestHandler):

def handle(self):
    cur_thread = threading.currentThread()
    line = self.rfile.readline()
    while True:
        line = self.rfile.readline()
        if not line: break
        print "%s wrote: %s" % (self.client_address[0], line.rstrip())
        self.wfile.write(line)
    return 

class ThreadedEchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass
########################################################################################
class MyFrame(wx.Frame):
def __init__(self, parent, title):
    wx.Frame.__init__(self, parent, -1, title, size=(1024,768))

    self.SetIcon(wx.Icon('sim.ico', wx.BITMAP_TYPE_ICO))
    self.SetBackgroundColour('#ece9d8')

    self.add_toolbar()
    self.Centre()

    #Flag variables
    self.isLogging = False
    self.threads = []
    server = ThreadedEchoServer(('localhost',9997), ThreadedEchoRequestHandler)
    t = threading.Thread(target=server.serve_forever)
    t.start()

    #Create data buffers

    #Some GUI Design Code

    #Create timer to read incoming data and scroll plot

    #Create start/stop button
    self.start_stop_button = wx.Button(self, label="Start", pos=(80,550), size=(150,150))
    self.start_stop_button.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False))
    self.start_stop_button.Bind(wx.EVT_BUTTON, self.onStartStopButton)

def add_toolbar(self):
    # Toolbar code

def onStartStopButton(self, event):
    if not self.isLogging:
        self.isLogging = True
        self.start_stop_button.SetLabel("Stop")
        call(["/home/user/Misc/socketTest/socketTest"])   
    else:
        self.isLogging = False
        self.start_stop_button.SetLabel("Start")                

def GetSample(self, msg):
### Manipulate Data from socket for matplotlib update

if __name__ == '__main__':
     app =wx.App(False)
     frame = MyFrame(None, 'Sim')
     frame.Show(True)
     app.MainLoop()

抱歉,我是 Python 新手。先感谢您。

4

1 回答 1

0

我不能说套接字通信的最佳方法是什么,它实际上取决于您的应用程序的需求、正在传输的数据的类型和格式、数量等。但我可以帮助与 GUI 应用程序集成.

在向 GUI 应用程序添加诸如套接字服务之类的东西时,需要注意一些关键原则。首先,为了保持 UI 对用户的响应,您不应该在 UI 事件处理程序或其他可能阻塞“用户可察觉”时间的回调中做任何事情。其次,您不应该从 UI 线程以外的线程创建或操作任何 GUI 元素。

因此,您从另一个线程运行 SocketServer(或您最终使用的任何东西)的直觉是好的。这使您可以将线程的全部注意力集中在处理通信上,而不必处理更复杂的事情,例如定期轮询、UI 事件处理等。它可以阻塞等待传入的数据。

有几种方法可用于将来自套接字的传入数据传送到 UI 线程。可能最简单的是使用 wxPython 的 wx.CallAfter 函数。它允许您指定一些应该调用的可调用对象,以及要传递给它的参数,然后它将导致该调用在此后不久在 UI 线程的上下文中发生。

于 2013-02-28T22:26:30.893 回答