• UDP c/s 模型


    server.c

    /* udp server.c */
    #include <string.h>
    #include <netinet/in.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <strings.h>
    #include <arpa/inet.h>
    #include <ctype.h>
    #define MAXLINE 80
    #define SERV_PORT 8000
    int main(void)
    {
    struct sockaddr_in servaddr, cliaddr;
    socklen_t cliaddr_len;
    int sockfd;
    char buf[MAXLINE];
    char str[INET_ADDRSTRLEN];
    int i, n;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);
    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    printf("Accepting connections ...
    ");
    while (1) {
    cliaddr_len = sizeof(cliaddr);
    n = recvfrom(sockfd, buf, MAXLINE,0, (struct sockaddr *)&cliaddr, &cliaddr_len);
    if (n == -1)
    perror("recvfrom error");
    printf("received from %s at PORT %d
    ",
    inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),
    ntohs(cliaddr.sin_port));
    for (i = 0; i < n; i++)
    buf[i] = toupper(buf[i]);
    n = sendto(sockfd, buf, n, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
    if (n == -1)
    perror("sendto error");
    }
    close(sockfd);
    return 0;
    }

    client.c

    /* udp client.c */
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <strings.h>
    #include <ctype.h>
    #define MAXLINE 80
    #define SERV_PORT 8000
    int main(int argc, char *argv[])
    {
    struct sockaddr_in servaddr;
    int sockfd, n;
    char buf[MAXLINE];
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
    servaddr.sin_port = htons(SERV_PORT);
    while (fgets(buf, MAXLINE, stdin) != NULL) {
    n = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
    if (n == -1)
    perror("sendto error");
    n = recvfrom(sockfd, buf, MAXLINE, 0, NULL, 0);
    if (n == -1)
    perror("recvfrom error");
    write(STDOUT_FILENO, buf, n);
    }
    close(sockfd);
    return 0;
    }
  • 相关阅读:
    六:Vue之父子组件间的三种通信方式
    五:Vue之ElementUI 表格Table与分页Pagination组件化
    四:Vue之VUEX状态管理
    三:Vue之混入(mixin)与全局混入
    二:Vue之ElementUI Form表单校验
    一:Vue之开发环境搭建
    变了,说不出来的感觉。
    20180320作业2:进行代码复审训练
    20180320作业1:源代码管理工具调查
    15软工课后作业02-15100120
  • 原文地址:https://www.cnblogs.com/xiangtingshen/p/10922711.html
Copyright © 2020-2023  润新知