注意事项:
1.client 和server 定义的发送和接收数据(结构)要相同。如:
client.c:
struct position_packet {
float pos_x[5];
float pos_y[5];
float pos_z[5];
}test_pkt;
server.c
struct position_packet {
float pos_x[10];
float pos_y[10];
float pos_z[10];
}test_pkt;
这样测出的结果就不相同。
---------------client.c------------------
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main()
{
int sockfd;
struct sockaddr_in servaddr; //结构体:http://blog.csdn.net/huqinwei987/article/details/23625823
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5000);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
struct position_packet {
float pos_x[5];
float pos_y[5];
float pos_z[5];
}test_pkt;
//for test udp send
printf("sizeof test_pkt:%lu\n",sizeof(test_pkt));
int i,number,y;
for ( i = 0; i < 5; ++i)
{
//产生随机数
test_pkt.pos_x[i] = 1;
test_pkt.pos_y[i] = 2;
test_pkt.pos_z[i] = 3;
printf("send x =%.2f,y=%.2f ,z=%.2f \n", test_pkt.pos_x[i],test_pkt.pos_y[i],test_pkt.pos_z[i]);
}
//sendto(sockfd, (char*)&test_pkt, sizeof(test_pkt), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
int state_send = sendto(sockfd, (char*)&test_pkt, sizeof(test_pkt), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
printf("sizeof test_pkt2:%lu and state_send=%d \n",sizeof(servaddr),state_send);
printf("send end !\n");
close(sockfd);
return 1;
}
---------------server.c------------------
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//servaddr.sin_addr.s_addr = inet_addr("192.168.1.238");
servaddr.sin_port = htons(5000);
bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
struct position_packet {
float pos_x[5];
float pos_y[5];
float pos_z[5];
}pwm_pkt;
while(1)
{
//int recvfrom(int sockfd,void *buf,int len,unsigned int lags,struct sockaddr *from,int *fromlen);
recvfrom(sockfd, (char*)&pwm_pkt, sizeof(pwm_pkt), 0, NULL, NULL);
printf("test sizeof(pwm_pkt)=%lu \n",sizeof(pwm_pkt));
int i=0;
for (i = 0; i < 5; ++i)
{
printf("i=%d \n", i);
printf("udp prot recv x=%.2f y=%.2f,z=%.2f \n",pwm_pkt.pos_x[i],pwm_pkt.pos_y[i],pwm_pkt.pos_z[i]);
}
}
close(sockfd);
}