我正在为服务器客户端架构制作一个简单的python客户机。当我将整数转换为C中的字符串并通过UDP发送到python客户端并试图将其转换为整数时,就会引发异常。我想这可能是因为C中的空终止字符串,所以我甚至尝试删除空终止符,但是没有joy。任何帮助都将不胜感激。
Python (客户端)代码片段,在这里我从服务器接收信息。
while True:
try:
p_ort = client_socket.recvfrom(1024)
portnumber = p_ort[0]
portnumber.strip()
#portnumber = portnumber[:-1]
#portnumber.rstrip("\0")
#this is where i try to convert the string into integer but the exception is thrown
try:
port_number = int(portnumber)
except:
print "Exception"
except:
print "timeout!"
break这是我从服务器发送值到客户端的代码片段。
void sendDataToClient( int sfd , int index )
{
char portNum[9] = {0};
sprintf( portNum , "%d" , videos[index].port ); //videos[index].port is an integer
if( sendto( sfd , &( portNum ) , 9 , 0 , (struct sockaddr *)&client , len ) == -1 )
{
perror( "sendto()" );
}
printf("\nClient Stuff sent!\n");
}发布于 2014-10-29 16:22:27
您可能只需要先去掉空。
例如:
portnumber = int(portnumber.strip('\x00'))我通常是如何去掉零终止符的。如果不看到端口号的打印,就很难知道这是否是正确的方法。
https://stackoverflow.com/questions/26635315
复制相似问题