C和Python程序之间的通信问题

时间:2014-10-16 06:58:58

标签: python c sockets python-2.7 udp

我正在尝试在C程序和python程序之间实现UDP通信协议。 C程序具有通过UDP端口(tx_port)作为二进制数据发送的结构。该程序还侦听任何接收数据的另一个端口(rx_port),然后将接收到的二进制输出打印到屏幕上。

python程序侦听tx_port并解压缩接收到的数据并将其打印到屏幕上。然后重新打包数据并通过UDP端口(rx_port)将其发回。

以下是我使用的C和Python程序。

C程序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <pthread.h>

#define BUFLEN 4096
#define RX_PORT 8888
#define TX_PORT 8889


// Structure data
struct data { 
    long frame_number;
    double time;
} tx_data, rx_data;
int dlen = sizeof(tx_data);

struct sockaddr_in si_me, si_other;
int tx_soc;
int slen = sizeof(si_other);
int recv_len;
char* buf;
pthread_t rx_thread;

void* receiver_thread(void *arg)
{
    int  i =0;
    while (1) {
        recv_len = recvfrom(tx_soc, buf, sizeof(rx_data), 0, (struct sockaddr *) &si_other, &slen);
        printf("\nReceived data :   %d\n", recv_len);
        for (i = 0; i < recv_len; i++) {
            printf("%x ", buf[i]);
        }
        printf("\n");
        fflush(stdout);
    };
}

void data_init(void) {
    tx_data.frame_number = 0;
    tx_data.time = 0;
};

int main(void)
{
    // Initialize data
    data_init();

    //create a UDP socket
    if ((tx_soc=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    {
        printf("Socket error!");
        exit(0);
    }

    // zero out the structure
    memset((char *) &si_me, 0, sizeof(si_other));
    memset((char *) &si_other, 0, sizeof(si_other));

    // Host socket address
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(RX_PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);

    // Remote socket address
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(TX_PORT);
    si_other.sin_addr.s_addr = htonl(INADDR_ANY);

    //bind sockets to the ports
    if( bind(tx_soc, (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
    {
        printf("Binding error!");
    }

    // Start reader thread.
    if (pthread_create(&rx_thread, NULL, &receiver_thread, NULL) != 0) {
        printf("\ncan't create thread");
    }

    //keep listening for data
    while(1)
    {
        // Allocate memory for receive buffer.
        buf = (char*) malloc(sizeof(rx_data));
        // Update data value.
        tx_data.frame_number++;
        printf("\nFrame numner: %ld", tx_data.frame_number);
        fflush(stdout);
        // Send data.
        if (sendto(tx_soc, (char*)&tx_data, dlen, 0, (struct sockaddr*) &si_other, slen) == -1)
        {
            printf("Sending error!");
        }
        sleep(1);
    }

    close(tx_soc);
    return 0;
}

Python程序

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
import struct

# Packet format string
packet_fmt = ''.join(['i',          # Frame number
                      'd',          # Frame time stamp
                      ])

s = struct.Struct(packet_fmt)

class Echo(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
        new_data = s.unpack(data)
        print new_data
        echo_data = s.pack(*new_data)
        self.transport.write(echo_data, (host, port))


reactor.listenUDP(8889, Echo())
reactor.run()

当我执行这两个程序时,我能够接收双方的数据。我能够在python中解压缩数据,打印,重新打包并发送它。

但在C端,接收的数据与发送的数据不匹配。我已经检查了python端,以确保重新打包的数据与原始数据匹配。

以下是C和Python程序的示例输出。我首先启动了python程序,然后启动了C程序。

enter image description here

我可能犯的错误是什么?

0 个答案:

没有答案