当服务器和客户机都用同一种语言编写时,我可以让它们协同工作(即两者都用c语言编写,或者两者都用python编写),但我不能让它们在c语言中与服务器和python中一起工作。目前,我想从c服务器向python客户机发送一个简单的字符串。在服务器sendall()在C中的实现如下(引用自Beej的指南):
int sendall(int socket, char * buf, int *len){
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
while(total < *len) {
n = send(socket, buf + total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
*len = total; // return number actually sent here
return n==-1?-1:0; // return -1 on failure, 0 on success
}
Python中的Client recvall()实现
def recv_one_message(sock):
lengthbuf = recvall(sock, 4)
length, = struct.unpack('!I', lengthbuf)
return recvall(sock, length)
def recvall(sock, count):
buf = ''
while count:
newbuf = sock.recv(count)
print newbuf
if not newbuf:
return None
buf += newbuf
count -= len(newbuf)
return buf
文章参考:https://www.cnpython.com/qa/212174