[英]Sending a structure over socket in c
I am writing a program which uses socket programming in c. 我正在编写一个在c中使用套接字编程的程序。
In this program a client and server keep transmitting and receiving data. 在此程序中,客户端和服务器将继续发送和接收数据。
When I send and receive integers over the socket using this kind of code 当我使用这种代码通过套接字发送和接收整数时
//in the program sending data
int data;
len= send(s,(char *)&(data),sizeof(data),0);
//in the program receiving data
int num;
len = recv(s,&num, sizeof(num) , 0);
The above code is working fine and I am able to transmit and receive numbers. 上面的代码工作正常,我能够发送和接收号码。
In one case I am trying to send a structure of the form 在一种情况下,我试图发送表单的结构
struct sample{
int num;
char chain[10*hops+10];
};
//in the program sending data
struct sample s1;
len= send(s,(char *)&(s1),sizeof(s1),0);
//in the program receiving data
struct sample s2;
len = recv(s,&s2, sizeof(s2) , 0);
In the example where I am trying to send and receive structure it is not working. 在我尝试发送和接收结构的示例中,它不起作用。 How to send and receive the struct successfully ?
如何成功发送和接收结构?
Note: 1) Hops is a pre defined variable.The value of hops is same in both the programs. 注意:1)Hops是一个预定义的变量,两个程序的Hops值相同。 2) By not working I meant : when I receive the struct and print the value in the the num.
2)不工作,我的意思是:当我收到结构体并在num中打印值时。 It is printing not the same value but zero!
它打印的值不相同,但为零!
if you are trying to send the struct you must use serialization and deserialization, read about that, you can start with : 如果您要发送该结构,则必须使用序列化和反序列化,请阅读有关内容,可以从以下内容开始:
Serialization issues while sending struct over socket 通过套接字发送结构时的序列化问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.