通信协议UDP

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define  _CRT_SECURE_NO_WARNINGS
#include <winsock2.h>
#pragma comment(lib,"ws2_32")
#include <Winsock2.h>
#include <stdio.h>

int main()
{
    //加载套接字
    WORD wVersionRequested;//WinSock库的版本号
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(1, 1);
    err = WSAStartup(wVersionRequested, &wsaData);
    
    //创建套接字
    SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);

    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(6000);

    //绑定套接字
    bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));

    char recvBuf[1000];//接收数据
    char sendBuf[1000];//发送数据
    char tempBuf[1000];//交换区数据

    SOCKADDR_IN addrClient;
    int len = sizeof(SOCKADDR);

    while (1)
    {
        //等待并接收数据
        recvfrom(sockSrv, recvBuf, 1000, 0, (SOCKADDR*)&addrClient, &len);
        if ('q' == recvBuf[0])
        {
            sendto(sockSrv, "q", strlen("q") + 1, 0, (SOCKADDR*)&addrClient, len);
            printf("结束!");
            break;
        }
        sprintf(tempBuf, "%s 说:%s", inet_ntoa(addrClient.sin_addr), recvBuf);

        printf("%s\n", tempBuf);
        //发送数据
        printf("请输入数据:\n");
        scanf("%s",sendBuf);
        sendto(sockSrv, sendBuf, strlen(sendBuf) + 1, 0, (SOCKADDR*)&addrClient, len);
    }
    //关闭套接字
    closesocket(sockSrv);
    
    return 0;
}

 

posted @ 2017-09-04 20:55  gd_沐辰  阅读(189)  评论(0编辑  收藏  举报