2014-01-17 55 views
0

我試圖發送一個160x120 uint32_t像素值的數組,我隨機生成。前兩個字節必須具有值(160和120),數據格式必須爲兩個值的int32_t。我如何以某種方式將int32_t的這兩個值插入到uint32_t數組的p [0]和p [1]中?第二個問題是:此代碼是否將字符串長度作爲數據的第一個字節發送?在p [0]之前?通過TCP的字符串長度

int main(int argc , char *argv[]) 
{ 
WSADATA wsa; 
SOCKET server_socket, client_socket; 
struct sockaddr_in server_addr, client_addr; 
int c, iResult; 
char sendbuf [DEFAULT_BUFLEN]; 
uint32_t* p; 
int32_t* z; 
int i; 

// Send uint8_t data to client 

p = (uint32_t*)sendbuf; 

p[0] = 120; // must be an int32_t value 
p[1] = 160; // must be an int32_t value 

srand (time(NULL)); 
for (i = 3; i < 19203; i++) 
{ 
     p[i] = rand() % 4294967295; //range 0-4294967294 */ 
     printf("%d\n", p[i]); 
} 
iResult = send(client_socket, sendbuf, (int32_t)strlen(sendbuf), 0); 
return 0; 

if (iResult == SOCKET_ERROR) 
{ 
    printf("Send failed. Error Code : %d\n", WSAGetLastError()); 
    iResult = 1; 
} 
else 
{ 
    printf("Bytes Sent: %d\n", iResult); 
    iResult = 0; 
} 

// shutdown the connection since no more data will be sent 
if (shutdown(client_socket, SD_SEND) == SOCKET_ERROR) 
{ 
    printf("Shutdown failed. Error Code : %d\n", WSAGetLastError()); 
    iResult = 1; 
} 

closesocket(client_socket); 
WSACleanup(); 

return iResult; 
} 
+0

否。它發送緩衝區中的內容,直到您指定的長度。 – EJP

回答

0

1則應將要在大端

2發送內容。它不會,服務器收到什麼樣的客戶端

iResult = send(client_socket, sendbuf, (int32_t)strlen(sendbuf), 0); 

發送

2

代替strlen(sendbuf)計算大小適當

//   number of pixels + int size + 2 ints for p[0] and p[1] 
int size = 160*120*sizeof(uint32_t) + 2 *sizeof(uint32_t); 
iResult = send(client_socket, sendbuf, size, 0); 

還要確保DEFAULT_BUFLEN等於超過size。如果你想要,你可以定義爲DEFAULT_BUFLEN