从客户端C发送套接字,服务器Python问题

时间:2018-11-09 18:57:04

标签: python c sockets

我当前的应用程序涉及一个C客户端,该客户端使用TCP将文件发送到Python服务器。它将产生文件的哈希并将信息发送回去。我可以将其与python客户端一起使用,但是在将客户端迁移到C时遇到问题。python服务器仍未完成(它需要将文件大小字符串转换为int,错误检查等)。

我现在最大的问题是服务器调用hash_type = connbuff.get_utf8()之后,它为我提供了哈希类型的第一个用户输入,然后关闭了连接。我知道这是get_utf8()的问题,但我对如何解决此问题感到困惑。我是否应该每次都仅从客户端发送任意数量的数据?请帮助我从我的错误中学习!任何建议/建议,不胜感激!谢谢=)

Server.py

def __init__(self,s):
    self.sock = s
    self.buffer = b''

def get_bytes(self,n):
    while len(self.buffer) < n:
        data = self.sock.recv(1024)
        if not data:
            data = self.buffer
            self.buffer = b''
            return data
        self.buffer += data

    data,self.buffer = self.buffer[:n],self.buffer[n:]
    return data

def get_utf8(self):
    while b'\x00' not in self.buffer:
        data = self.sock.recv(1024)
        if not data:
            return ''
        self.buffer += data

    data,_,self.buffer = self.buffer.partition(b'\x00')
    return data.decode()

我的Buffer类get_utf8()和get_bytes()看起来像这样...

#include <sys/socket.h>
  ... more includes ...

#define PORT_NUMBER 2345
#define SERVER_ADDRESS "127.0.0.1"

char *inputString(FILE* fp, size_t size){
    ... string input code ...
}

int main () {
    int server_socket, connection_status;
    struct sockaddr_in serverAddress;
    char *hashType;
    char *fileName;
    char send_buffer[4000];
    FILE * file_to_send;
    int file_size;

/* Connect to Server */
    ... connect to server code ...

/* Get Hash an File User Input */
printf("Enter hash type: ");
hashType = inputString(stdin, 10);
printf("Hash type: %s\n", hashType);

printf("Enter file name: ");
fileName = inputString(stdin, 10);
printf("File Name: %s\n");

/* Send User Input */
send(server_socket, hashType, sizeof(hashType), 0);
send(server_socket, fileName, sizeof(fileName), 0);

/* Open File, Get Size, Convert to String */
file_to_send = fopen(fileName, "rb");
fseek(file_to_send, 0, SEEK_END);
file_size = ftell(file_to_send);
fseek(file_to_send, 0, SEEK_SET);

int l = snprintf(NULL, 0, "%d", file_size);
char *str_file_size;
asprintf(&str_file_size, "%i", file_size);
printf("%s\n", str_file_size);

/* Send File Size and File */
send(server_socket, str_file_size, sizeof(str_file_size), 0);

while(!feof(file_to_send)) {
    fread(send_buffer, 1, sizeof(send_buffer) - 1, file_to_send);
}
send(server_socket, send_buffer, sizeof(send_buffer), 0);

return 0;

Client.c

>>> import camelot
>>> tables = camelot.read_pdf('file.pdf')
>>> type(tables[0].df)
<class 'pandas.core.frame.DataFrame'>
>>> tables[0].to_csv('file.csv')

}

1 个答案:

答案 0 :(得分:1)

get_utf8希望从套接字读取一个以空终止的UTF-8编码的字符串。在C代码中,您发送sizeof(hashType)hashType是一个指针,因此您恰好要发送4或8个字节(取决于32位或64位体系结构)。您可能需要strlen(hashType)+1(NULL为+1)。与文件名相同。

get_utf8也会读取直到看到空值。如果从未看到,则返回空字符串,这将导致接收代码中断并关闭连接。