UDP客户端demo

#include
#include
using namespace std;
#define SERVER_IP "192.168.0.102"

//导入依赖的库
#pragma comment(lib,"ws2_32.lib")

int main() {

    //1、加载库
    WORD wVersionRequested; //设置要加载的库的版本号
    WSADATA wsaData;        //接收加载库的结果
    int err;
    wVersionRequested = MAKEWORD(2, 2);
    err = WSAStartup(wVersionRequested, &wsaData);

    if (err != 0) 
    {
        //加载失败
        printf("WSAStartup failed with error: %d\n", err);
        return 1;
    }
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) 
    {
        //版本不对
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();//卸载这个错误版本
        return 1;
    }
    else
    {
        //加载成功
        printf("The Winsock 2.2 dll was found okay\n");
    }




    // 2、创建套接字
    SOCKET sock = INVALID_SOCKET;                   //将soct初始化为不合法
    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//address family, type, protocol
    if (INVALID_SOCKET == sock)                     //把常量写在左边,在编译期就能发现  把==误写成= 的问题
    {
        cout << "socket error: " << WSAGetLastError() << endl;
        WSACleanup();//上面已经加载库成功,所以需要卸载库
        return 1;
    }
    else
    {
        cout << "socket success" << endl;
    }



    int nRecvNum = 0;           //接收长度
    int nSendNum = 0;           //发送长度
    char recvBuf[1024] = "";    //接收缓冲区
    char sendBuf[1024] = "";    //发送缓冲区
    //存储服务端的地址信息
    sockaddr_in addrServer;
    addrServer.sin_family = AF_INET;
    addrServer.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);//服务器端的ip地址
    addrServer.sin_port = htons(54367);
    while (1) {
        // 3、发送数据
        gets_s(sendBuf);//从控制台读取用户输入的数据,存入senBuf
        //发送成功的返回值 = 发送函数(socket,发送缓冲区,发送缓冲区长度,标志位,
        //                              记录接收端的sockaddr结构体,记录接收端的sockaddr结构体的长度)
        nSendNum = sendto(sock, sendBuf, sizeof(sendBuf), 0, (sockaddr*)&addrServer, sizeof(addrServer));
        if (SOCKET_ERROR == nSendNum) {
            cout << "send error:" << WSAGetLastError() << endl;
            break;
        }
        else {
            cout << "send success" << endl;
        }
        // 4、接收数据,recvfrom是默认阻塞
        //recvfrom函数后两个值是用来保存发送端的地址信息和端口
        nRecvNum = recvfrom(sock, recvBuf, sizeof(recvBuf), 0, 0, 0);//最后两个可以填0,因为已经知道服务器的地址
        if (nRecvNum > 0) {
            //接收数据成功,打印接受的数据
            //inet_ntoa 把u_long类型的ip地址转换成字符串类型
            cout << "ip: " << inet_ntoa(addrServer.sin_addr) << " say: " << recvBuf << endl;
            cout << "Please enter what you want to say. -->";
        }
        else if (nRecvNum == 0) {
            cout << "connect close" << endl;
            break;
        }
        else {
            cout << "recv error:" << WSAGetLastError() << endl;
            break;
        }
    }


    //5、关闭套接字、卸载库
    closesocket(sock);
    //6、卸载库
    WSACleanup();
    return 0;
}

你可能感兴趣的:(学习,算法)