c udp server client demo --待调试

Posted luckygxf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    int cliAddrLen = sizeof(cliAddr);
    while (1) {
        char buff[BUFFSIZE];
        int addrLen = sizeof(cliAddr);
        int readCount = recvfrom(serverSocketFd, buff, BUFFSIZE, 0, (struct sockaddr*)&cliAddr, &addrLen);
        buff[readCount] = ‘‘;
        printf("Receive from client:%s
", buff);
        sendto(serverSocketFd, buff, BUFFSIZE, 0, (struct sockaddr *)&cliAddr, sizeof(addrLen));
    }


    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");

    int 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;
}

  

以上是关于c udp server client demo --待调试的主要内容,如果未能解决你的问题,请参考以下文章

基于TCP与UDP协议的socket通信

基于TCP与UDP协议的socket通信

udp server client

UDP也需要现有Server端,然后再有Client端

libuv udp server和client

linux+udp+server+client