zoukankan      html  css  js  c++  java
  • c udp server client demo

    server.c

    //
    // Created by gxf on 2020/2/7.
    //
    
    #include <stdio.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    #include <stdlib.h>
    
    #define BUFFSIZE 1024
    
    int main(){
        int serverSocketFd = socket(AF_INET, SOCK_DGRAM, 0);
        struct sockaddr_in serverAddr;
        serverAddr.sin_family = AF_INET;
        serverAddr.sin_port = htons(1234);
        serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    
        int ret = bind(serverSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
        if (ret) {
            fprintf(stderr, "bind fail");
            exit(1);
        }
    
        struct sockaddr_in cliAddr;
        socklen_t cliAddrLen = sizeof(cliAddr);
        while (1) {
            char buff[BUFFSIZE];
            int readCount = recvfrom(serverSocketFd, buff, BUFFSIZE, 0, (struct sockaddr*)&cliAddr, &cliAddrLen);
            buff[readCount] = '';
            printf("Receive from client:%s
    ", buff);
            sendto(serverSocketFd, buff, BUFFSIZE, 0, (struct sockaddr *)&cliAddr, cliAddrLen);
        }
    
    
        return 0;
    }
    

      

      client.c

    //
    // Created by gxf on 2020/2/7.
    //
    
    #include <stdio.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    
    #define BUFSIZE 1024
    
    int main(){
        int clientSocketFd = socket(AF_INET, SOCK_DGRAM, 0);
        struct sockaddr_in serverAddr;
        serverAddr.sin_family = AF_INET;
        serverAddr.sin_port = htons(1234);
        serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    
        socklen_t addrLen = sizeof(serverAddr);
        while (1) {
            char buff[BUFSIZE];
            printf("Enter msg send to server:");
            scanf("%s", buff);
    
            sendto(clientSocketFd, buff, BUFSIZE, 0, (struct sockaddr*)&serverAddr, addrLen);
            int readCount = recvfrom(clientSocketFd, buff, BUFSIZE, 0, (struct sockaddr*)&serverAddr, &addrLen);
            buff[readCount] = '';
            printf("Receive from server:%s
    ", buff);
        }
    
        return 0;
    }
    

      

      

  • 相关阅读:
    JSON
    什么是Jsonp?
    用border做三角形
    前端模块化
    Web 前端
    前端性能优化
    Ajax的原理
    node.js基础语法
    【真·新手初篇】菜鸟们都戳进来看看(欢迎大神指导)
    2019.11.20 开启一天的工作
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12274979.html
Copyright © 2011-2022 走看看