[英]sending an array of structs across a socket
如果我有一個結構數組怎么辦。 我可以通過套接字發送結構數組嗎? 結構體的大小將不斷更新,我可以隨時打印出結構體的內容。 我希望這是有道理的,我的解釋可能沒有被清除。 對於某些領域,我的語法絕對不正確,這只是我認為它看起來像的一小部分。 我只是需要一些指導。
這將通過套接字發送結構數組。
void sendOpenMessage(int num0, int num1, int num2){
struct openMessage{
int num0;
int num1;
int num2
};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;
int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sent\n");
}
i++;
}
這將接收結構並在消息中顯示內容
struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failed\n");
printf("Error code: %d\n", errno);
}
//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%d\n",open[i].num0);
printf("%d\n", open[i].num1);
printf("%d\n", open[i].num2);
}
}
首先,您需要閱讀有關字節順序和序列化的信息。
其次, length
是整個數組的大小,因此當i
為零時,您發送整個數組,當i
為 1 時,您發送除第一個元素外的所有元素以及末尾的一些垃圾,依此類推。 第三,當接收到你遍歷數組的sizeof(the struct)
成員時。 你不想遍歷整個數組嗎?
當您說the struct size will be updated continuously
,您是指數組中的元素數嗎? 您的結構具有固定大小。
如果您要發送可變數量的數據,即如果您想發送一次具有一個長度而另一次具有另一個長度的數據,或者即使您希望數組中的元素數量動態更新,那么您必須通過套接字發送該大小,並在數據之前發送它。 先發送size,在接收端先讀取,然后接收端就知道要讀取多少數據了,更重要的是,數據在哪里結束,這樣以后數據多了就不會全混了向上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.