#include #define SUCCESS 0
#define BUFF_LEN 1024
#define PORT 8083
int CreateUDPScoket()
{
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sfd == -1){
printf("Create Socket failed!\n");
}
return sfd;
}
int BindPortUDP(int sfd)
{
struct sockaddr_in addr;
memset(&addr, 0 , sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY); //注意网络序转换
addr.sin_port = htons(PORT); //注意网络序转换
int ret = bind(sfd, (struct sockaddr *)&addr ,sizeof(addr));
if(ret < 0)
{
printf("socket bind fail!\n");
return -1;
}
return SUCCESS;
}
void handle_udp_msg(int fd)
{
char buf[BUFF_LEN]; //接收缓冲区,1024字节
socklen_t len;
int count;
struct sockaddr_in clent_addr; //clent_addr用于记录发送方的地址信息
while(1)
{
memset(buf, 0, BUFF_LEN);
len = sizeof(clent_addr);
count = recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&clent_addr, &len); //recvfrom是拥塞函数,没有数据就一直拥塞
if(count == -1)
{
printf("recieve data fail!\n");
return;
}
printf("client:%s\n",buf); //打印client发过来的信息
memset(buf, 0, BUFF_LEN);
sprintf(buf, "I have recieved %d bytes data!\n", count); //回复client
printf("server:%s\n",buf); //打印自己发送的信息给
sendto(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&clent_addr, len); //发送信息给client,注意使用了clent_addr结构体指针
}
}
int main()
{
int Serverfd = CreateUDPScoket();
BindPortUDP(Serverfd);
handle_udp_msg(Serverfd);
return 0;
}