UDP 프로토콜, socket 프로그래밍, 윈도우즈 API로 호출, 클라이언트와 서버 구현

2360 단어 운영 체제
서버 섹션:
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!
"); exit(1); } printf("Receving datagrams ...
"); 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
"); flag = 1; }else if(strcmp(RecvBuf, "file sended -- 123")==0){ printf("file have received!
"); fclose(fp); flag = 0; }else{ if(flag == 1){ count++; fprintf(fp ,"%s\t",RecvBuf); if((count%5)== 0){ fprintf(fp ,"
"); } }else{ printf("Received Data: %s
", RecvBuf); } } } printf("Finished receiving. Closing socket.
"); closesocket(RecvSocket); // , printf("Exiting.
"); return 0; }

좋은 웹페이지 즐겨찾기