基于UDP的服务器端和客户端知识详解

UDP(用户数据报协议)是一种无连接的通信协议。这里详细讲解基于UDP的服务器端和客户端:

服务器端:

1. 创建UDP套接字:socket(AF_INET, SOCK_DGRAM, 0);

2. 绑定IP地址和端口:bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));

3. 接收客户端数据:recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientaddr, &len);

4. 发送数据给客户端:sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientaddr, len);

5. 关闭套接字:close(sockfd);服务器端代码示例:

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <unistd.h>  
#include <sys/socket.h>  
#include <arpa/inet.h>  

int main() { 
    int sockfd;
    struct sockaddr_in serveraddr, clientaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);   //创建UDP套接字 

    serveraddr.sin_family = AF_INET;           
    serveraddr.sin_port = htons(9999);        
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    memset(serveraddr.sin_zero, 0, sizeof(serveraddr.sin_zero)); 

    bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));   //绑定地址和端口

    while(1) {
        socklen_t len;
        char buf[1024];
        recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientaddr, &len);   //接收数据
        printf("Receive from client: %s\n", buf);
        sendto(sockfd, "Hello", 6, 0, (struct sockaddr *)&clientaddr, len);   //发送数据
    }

    close(sockfd);  //关闭套接字
}

客户端:

1. 创建UDP套接字:socket(AF_INET, SOCK_DGRAM, 0);

2. 发送数据:sendto(sockfd, “Hello”, 6, 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));

3. 接收服务器数据:recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&serveraddr, &len);

4. 关闭套接字:close(sockfd);客户端代码示例:

#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <string.h>  
#include <sys/socket.h>
#include <arpa/inet.h>  

int main() { 
    int sockfd;
    struct sockaddr_in serveraddr; 

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);  //创建UDP套接字

    serveraddr.sin_family = AF_INET;        
    serveraddr.sin_port = htons(9999);       
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");  

    sendto(sockfd, "Hello", 6, 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));   //发送数据

    char buf[1024];
    socklen_t len = sizeof(serveraddr);
    recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&serveraddr, &len);   //接收数据
    printf("Receive from server: %s\n", buf);

    close(sockfd);   //关闭套接字
}
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论