[英]Sending struct over socket in C
I am trying to send struct over sockets. The connection works fine with arrays, but with a simple struct the server recieves only Recv - 1 - 1
If i change the ID or status to another number(while the client is running), it recieves nothing, but the client has sended.我正在尝试通过 sockets 发送结构。与 arrays 的连接工作正常,但使用简单的结构,服务器仅Recv - 1 - 1
如果我将 ID 或状态更改为另一个数字(客户端正在运行时),它会收到什么都没有,但是客户已经发送了。 And if i change it back to ID=1 and status=1 it send it again and recieve it correctly.如果我将其改回 ID=1 和 status=1,它会再次发送并正确接收。
Client-Side:客户端:
void func()
{
printf("Send - %i - %i\n", mRELAIS.ID, mRELAIS.status);
send(sockfd,&mRELAIS,sizeof(struct RELAIS),0);
}
Output: Send - 1 - 1
respectively Send - 1 - 0
Output: Send - 1 - 1
-1-1分别Send - 1 - 0
-1-0
Where i change it on the Client-Side:我在客户端更改它的地方:
if(temperature>(g_Value+g_PlusMinus) && relais[0]==0)
{
printf("%.1lf°C Relais wird 1 Soll %.1lf\n", temperature,(g_Value+g_PlusMinus));
mRELAIS.ID=1;
mRELAIS.status=1;
func();
}
else if(temperature<(g_Value-g_PlusMinus) && relais[0]==1)
{
printf("%.1lf°C Relais wird 0 Soll %.1lf\n", temperature,(g_Value-g_PlusMinus));
mRELAIS.ID=1;
mRELAIS.status=0;
func();
}
Server-Side:服务器端:
for (;;)
{
recv(connfd, &mRELAIS, sizeof(struct RELAIS),0);
printf("Recv - %i - %i\n", mRELAIS.ID, mRELAIS.status);
....
}
Output: Send - 1 - 1
respectively Output:分别Send - 1 - 1
-1-1
Does anyone have a suggestion to solve the problem?有没有人有解决问题的建议? Thanks.谢谢。
Not sure if this is your immediate problem but your receive code is wrong.不确定这是否是您的直接问题,但您的接收代码是错误的。 Tco is a steaming protocol, not a message oriented one. Tco 是一种流协议,而不是面向消息的协议。 You might receive a 50 byte send as 50 one byte receives.您可能会收到一个 50 个字节的发送,因为 50 个一个字节会收到。 Or 2 25 bytes receives.或 2 个 25 字节接收。 You must lipp on recv till you have the entire send.你必须 lipp on recv 直到你有整个发送。 There s in turn means that the receiver has to know the message size somehow反过来意味着接收者必须以某种方式知道消息的大小
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.