本帖最后由 yanghelovehuang 于 2018-6-27 15:52 编辑
各位大虾 我按照别人的实例写了个简单的udp服务器和客户端通讯的问题,写好后运行服务端 阻塞到recvfrom 可是运行客户端发送一个数据还是在那阻塞,没有循环接受就接收一次数据.
当我把实例运行后能够成功接收,我然后按照实力改把变量改的都和实例的一样了,可是运行客户端发送数据服务器还是接收不到。
运行我写的服务器运行实例客服端能够接收到数据,真搞不懂是什么原因,客户端代码都一摸一样了,为啥就是接收不到我写的客户端的数据呢?我用的是Ubuntu 12.04
附件:我写的服务器:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#define N 128
int main(int argc, const char *argv[])
{
int sockfd;
struct sockaddr_in serveraddr, clientaddr;
socklen_t addrlen = sizeof(struct sockaddr_in);
char buf[N];
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
printf("create socket failed\n");
return -1;
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(atoi(argv[2]));
if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
{
printf("fail to bind\n");
return -1;
}
recvfrom(sockfd, buf, N, 0, (struct sockaddr *)&clientaddr, &addrlen);
printf("%s\n", buf);
close(sockfd);
return 0;
}
我写的客户端:
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define N 128
int main(int argc, const char *argv[])
{
int sockfd;
struct sockaddr_in serveraddr;
socklen_t addrlen = sizeof(struct sockaddr_in);
char buf[N] = "i am client";
if(sockfd = socket(AF_INET, SOCK_DGRAM, 0) < 0)
{
printf("fail to socket\n");
return -1;
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(atoi(argv[2]));
sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
close(sockfd);
return 0;
}
|