实现UDP协议,socket编程,调用到windowsAPI,实现客户端和服务器

服务器部分:

利用socket

语言:C 语言

环境:可以编译的环境

代码如下:

#include 
#include 
#include 

int main()
{
    WSADATA wsaData;
    SOCKET RecvSocket;
    struct sockaddr_in RecvAddr;
    int port = 27015;
    char RecvBuf[1024];
    int BufLen = 1024;
    int len =0;
    int flag = 0;
    FILE* fp;
    struct sockaddr_in SenderAddr;
    int SenderAddrSize = sizeof(SenderAddr);
    //
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    RecvAddr.sin_family = AF_INET;
    RecvAddr.sin_port = htons(port);
    RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    // 用于多方面数据的接受,符合服务器的数据传输的模式
    if(bind(RecvSocket, (SOCKADDR* )&RecvAddr, sizeof(RecvAddr))< 0){
        printf("Error: bind failed!\n");
        exit(1);
    }
    printf("Receving datagrams ... \n");

    for(; ; ){
        static int count = 0;
        static int fileNum = 0;
        char filenameTmp[20];
        len = recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR* )&SenderAddr, &SenderAddrSize);
        sendto(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR* )&SenderAddr, &SenderAddrSize);
        //printf("Data Success, and sended!");
        RecvBuf[len] = '\0';
        //  此处的判断是为了文件接收的转换的情况, 注意加强自身的对UDP 协议的理解;
        if(strcmp(RecvBuf, "file send -- 123")==0){
            fileNum++;
            sprintf(filenameTmp, "receive%d.txt", fileNum);
            fp = fopen(filenameTmp, "a+");
            printf("file will received\n");
            flag = 1;
        }else if(strcmp(RecvBuf, "file sended -- 123")==0){
            printf("file have received!\n");
            fclose(fp);
            flag = 0;
        }else{
            if(flag == 1){
                count++;
                fprintf(fp ,"%s\t",RecvBuf);
                if((count%5)== 0){
                    fprintf(fp ,"\n");
                }

            }else{
                printf("Received Data: %s\n", RecvBuf);
            }

        }

    }


    printf("Finished receiving. Closing socket. \n");
    closesocket(RecvSocket); // 销毁套接字, 逻辑严密性

    printf("Exiting.\n");
    return 0;
}

你可能感兴趣的:(操作系统)