UDP服务器客户端相互通信

UDP服务器、客户端之间的相互通信

之前的版本只能实现UDP服务器之间单发单收,此版本能实现UDP服务器和客户端之间的相互通信。

见下面的程序:

udp_server.c

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT 3333

int main()
{
    int sockfd;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int addrlen = sizeof(struct sockaddr);
    int addrinlen = sizeof(struct sockaddr_in);
    int recvbytes;
    char buf[512];
    char buf1[1024] = {0};

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        fprintf(stderr, "socket error:%s\n", strerror(errno));
	exit(1);
    }

    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);
    
    if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        fprintf(stderr, "bind error:%s\n", strerror(errno));
	exit(1);
    }
while(1)
{
    memset(buf, 0, sizeof(buf));
    if((recvbytes = recvfrom(sockfd, buf, 512, 0, (struct sockaddr *)&client_addr, &addrinlen)) < 0)
    {
        fprintf(stderr, "recvfrom error:%s\n", strerror(errno));
	exit(1);
    }
    buf[recvbytes] = '\0';
    printf("receive from client is %s", buf);

    printf("Please input:");
    fgets(buf1, 1024, stdin);
    sendto(sockfd, buf1, 1024, 0, (struct sockaddr *)&client_addr, sizeof(struct sockaddr));
}
    close(sockfd);

    return 0;
}

udp_client.c

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT 3333

int main()
{
    int sockfd;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int addrlen = sizeof(struct sockaddr);
    int addrinlen = sizeof(struct sockaddr_in);
    char buf[1024] = "hello world";
    char buf1[1024];

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        fprintf(stderr, "socket error:%s\n", strerror(errno));
	exit(1);
    }

    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    //server_addr.sin_addr.s_addr = inet_addr("192.168.1.222");
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);
    
    while(1)
    {
        printf("Please client input:");
	fgets(buf, 1024, stdin);
       
        if(sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
        {
            fprintf(stderr, "sendto error:%s\n", strerror(errno));
	    //perror("sendto");
	    exit(1);
        }
    

    memset(buf1, 0, sizeof(buf1));
    bzero(&client_addr, sizeof(struct sockaddr_in));

    if(recvfrom(sockfd, buf1, sizeof(buf1), 0, (struct sockaddr *)&client_addr, &addrlen) < 0)
    {
        fprintf(stderr, "client recvfrom error:%s\n", strerror(errno));
	exit(1);
    }
    printf("receive from server:%s\n", buf1);

}
    close(sockfd);

    return 0;

}
运行结果:

UDP服务器客户端相互通信_第1张图片

UDP服务器客户端相互通信_第2张图片


你可能感兴趣的:(C语言)