UDP服务端demo

#include
#include
using namespace std;

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

int main(){
    cout << "-------服务端--------" << endl;
	//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=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (INVALID_SOCKET==sock)
    {
        cout << "socket error: "<<WSAGetLastError() << endl;
        WSACleanup();//上面已经加载库成功,所以需要卸载库
        return 1;
    }
    else
    {
        cout << "socket success" << endl;
    }
	

	// 3、绑定ip地址
    sockaddr_in addrServer;                         //设置服务端信息
    addrServer.sin_family = AF_INET;                //使用的协议族
    addrServer.sin_port = htons(54367);             //端口,使用htons把主机字节序转换成网络字节序(大端)
    addrServer.sin_addr.S_un.S_addr = INADDR_ANY;   //绑定任意网卡
    //绑定
    err = bind(sock, (sockaddr*)&addrServer, sizeof(addrServer));   
    //结果判断
    if (SOCKET_ERROR == err) 
    {
        cout << "bind error: " << WSAGetLastError() << endl;
        closesocket(sock);                          //关闭套接字
        WSACleanup();                               //上面已经加载库成功,所以需要卸载库
        return 1;
    }
    else 
    {
        cout << "bind success" << endl;
    }



    int nRecvNum = 0;
    int nSendNum = 0;
    char recvBuf[1024] = "";
    char sendBuf[1024] = "";
    //存储给服务端发数据的客户端的地址信息
    sockaddr_in addrClient;
    int addrClientSize = sizeof(addrClient);
	while (1) {
		// 4、接受数据,recvfrom是阻断类型的函数
        nRecvNum = recvfrom(sock,recvBuf,sizeof(recvBuf),0,(sockaddr*)&addrClient,&addrClientSize);
        if (nRecvNum > 0) {
            //接收数据成功,打印接受的数据
            //inet_ntoa 把u_long类型的ip地址转换成字符串类型
            cout<<"ip: "<<inet_ntoa(addrClient.sin_addr) <<"    port" << addrClient.sin_port<< "     say: " << recvBuf << endl;
        }
        else if (nRecvNum==0) {
            cout << "connect close" << endl;
            break;
        }
        else {
            cout << "recv error:" << WSAGetLastError() << endl;
            break;
        }


        // 5、发送数据
        gets_s(sendBuf);
        nSendNum = sendto(sock,sendBuf,sizeof(sendBuf),0, (sockaddr*)&addrClient,sizeof(addrClient));
        if (SOCKET_ERROR == nSendNum) {
            cout << "send error:" << WSAGetLastError() << endl;
            break;
        }
        else{
            cout << "send success" << endl;
        }
        
	}

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

	return 0;
			
}

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