2014-10-29 62 views
0

我正在爲服務器客戶端體系結構製作一個簡單的python客戶端。問題出現時,我將一個整數轉換爲C中的字符串,並通過UDP發送給python客戶端,並嘗試將其轉換爲整數,引發異常。我認爲這可能是因爲在C終止空字符串,所以我甚至試圖消除空終止符,但沒有喜悅。任何幫助將不勝感激。將空終止字符串轉換爲Python中的Int

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"); 
    } 
+0

提供一個簡單的,最小的例子可以幫助人們幫助你。在這種情況下,只是你收到的數據(python方)和解釋它的代碼。 – goncalopp 2014-10-29 16:13:52

+0

我已經編輯我的代碼,只是爲了創造問題的極限。 – 2014-10-29 16:21:29

+0

'portnumber.strip()'不改變'portnumber',但是''返回'被剝離的字符串。 – ch3ka 2014-10-29 16:24:00

回答

1

您可能只需要首先去掉null。

例如:

portnumber = int(portnumber.strip('\x00')) 

是如何我通常脫掉空終止子。這將是很難知道這是否是正確的方法,雖然沒有看到一個打印的端口號。

+0

絕對精彩!爲我工作! 我無法得到的是,我一直在嘗試其他方法來剝離那個空終止符,但似乎沒有工作。我嘗試了'portnumber.rstrip(「\ 0」)',但這似乎沒有任何幫助。這是爲什麼? – 2014-10-29 16:28:31

+0

@AliAbbasJaffri因爲在C中,空字節\ 0實際上是十六進制值0x00,它在python中是\ x00。 – ballsatballsdotballs 2014-10-29 16:31:14

+0

這應該來得方便!非常感謝你的幫助! – 2014-10-29 16:33:25