2016-06-27 72 views
1

我有一個python套接字服務器,它將字符串發送到打印該字符串的C程序(客戶端),然後將其發送回打印它的python程序。通信是有效的,但如果它發送一個長字符串,然後是一個短字符串,那麼當前和之前的數據就會合並。這裏的例子:C和python代碼之間的套接字通信

輸出:

5.0standing0.0    //That is how it should look like 
5.0walk0ing0.055111512313e-17 //After the long string 

Python代碼(剛剛被稱爲一個循環):

import socket 
import sys 

# Create a TCP/IP socket 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# Bind the socket to the port 
server_address = ('localhost', 8888) 
print >>sys.stderr, '\nstarting up on %s port %s\n' % server_address 
sock.bind(server_address) 

# Listen for incoming connection 
sock.listen(1) 

def send_control(state,xdiff,xactual): 
    connection, client_address = sock.accept() 
    connection.sendall(str(xactual)+str(state)+str(xdiff)) 
    data = connection.recv(2000) 
    print data 
    data = '\0' 

C代碼(被稱爲一個循環太):

void comm_func() 
{ 
    int sock; 
    int i=0; 
    struct sockaddr_in server; 
    char message[1024] , server_reply[2000]; 

    //Create socket 
    sock = socket(AF_INET , SOCK_STREAM , 0); 
    if (sock == -1) 
    { 
     printf("Could not create socket"); 
    } 
    // puts("Socket created"); 

    server.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    server.sin_family = AF_INET; 
    server.sin_port = htons(8888); 

    //Connect to remote server 
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) 
    { 
     perror("connect failed. Error"); 
    } 

    // Receive a reply from the server 
    if(recv(sock , server_reply , 2000 , 0) < 0) 
    { 
     puts("recv failed"); 
    } 
    puts(server_reply); 
    write(sock,server_reply,50); 
    for (i=0; i< strlen(server_reply); i++) 
    { 
    server_reply[i] = '\0'; 
    } 
    close(sock); 
} 

任何人都可以幫助我嗎?

+2

收到的字符串不是空終止的,所以[UB](https://en.wikipedia.org/wiki/Undefined_behavior)。輕鬆修復'char server_reply [2000] = {0}' – LPs

+2

不要指望'recv()'儘可能地返回它所告訴的。檢查它的回報值,永遠。也測試它爲'0'。考慮到TCP是以流爲導向的。 N發送可能觸發M個接收,其中N> M或N alk

+0

投票將其視爲對文檔的隱式調用,這似乎並未出現。 – alk

回答

1

變化

// Receive a reply from the server 
    if(recv(sock , server_reply , 2000 , 0) < 0) 
    { 
     puts("recv failed"); 
    } 

分爲:

ssize_t len; 
    // Receive a reply from the server 
    if((len = recv(sock , server_reply , 2000 , 0)) < 0) 
    { 
     puts("recv failed"); 
     close(sock); 
     return -1; 
    } 
    server_reply[len] = 0; 

由於兩個@LP和@ack提的意見,問題是,短消息不NUL終止,這是正常的套接字通信,其中0是要發送的有效字節。

相關問題