简体   繁体   English

从Network C ++接收数据

[英]Receiving data from Network C++

I have a python function to send data over the network by data gram socket.In the receiver end i have to use c++ to receive that data But the receiver can't receive any meaningful data.What should be used to get the string in the exact format it was sent? 我有一个python函数通过数据报套接字在网络上发送数据。在接收器端,我必须使用c ++接收该数据,但是接收器无法接收任何有意义的数据。应该使用什么来获取字符串发送的确切格式?

Python code Python代码

def send(self, command):
        segments = command.split() # split command on spaces
        if len(segments) < 5 or segments[1] not in self.hosts or segments[2] not in self.hosts: # sanity check
            print('invalid arguments')
            return
        else:
            h1 = map(int, segments[1].split('.'))# segment 1 contains a IP address
            h2 = map(int, segments[2].split('.'))# segment 2 contains an IP address
            fmt = '4s4B4Bh' + segments[3] + 's'# segemt 3 is string length segment 4 is a string
            buf = struct.pack(fmt, segments[0], h1[0], h1[1], h1[2], h1[3], h2[0], h2[1], h2[2], h2[3], int(segments[3]), ' '.join(segments[4:]))
            print('sending to {0}'.format(segments[1])) # print a message before sending to source
            self.s.sendto(buf, (segments[1], self.port)) # send to source
            #self.s.sendto(command, (segments[1], self.port)) # send to source

C++ code C ++代码

bytes_received = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*) &client_address, &addrlen);
        //print(buffer);
        if(bytes_received==-1)
        {
            perror("recvfrom");
            printf("error %s\n",strerror(errno));
        }

        printf("[%s:%hu]: %s \n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buffer);

All the sockets are created properly 所有套接字均已正确创建

If you receive something like "send ???????" 如果收到类似“发送???????”的信息 I'd expect encoding problems during sending. 我希望在发送过程中出现编码问题。 '?' '?' is 0x3F (dec 63) which usually comes from characters out of basic ASCII (less then 127) table. 是0x3F(dec 63),通常来自基本ASCII表(小于127)中的字符。 I'm not familiar with python, but can you ensure you use proper (eg UTF-8, for sure not UTF-16/32 and perhaps not ASCII) encoding while transforming python string into byte array? 我不熟悉python,但是您可以确保在将python字符串转换为字节数组时使用正确的编码(例如UTF-8,确保不是UTF-16 / 32,也许不是ASCII)吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM