C++ SOCKET编程求指教
我正在学习C++编程,根据教学视频学习了SOCKET编程,编译时遇到错误:LNK1104,无法打开文件"win2_32.lib"操作系统:windows10
操作系统版本:1909(OS内部版本:18363.752)
程序代码:
#include <cstdio> //<stdio.h> #include <cstdlib> //<stdlib> #include <WinSock2.h> #pragma comment(lib,"win2_32.lib")//加载 ws2_32.dll void main(void) { //1:初始化windows套间字 WSAData wsaData; int ret; if ((ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) { printf("WSAStartup failed with error %d\n", ret); return; } //2:创建监听套件字 SOCKET listeningSocket; if ((listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { printf("socket failed with error %d\n", WSAGetLastError()); WSACleanup(); return; } //3:把套件字和服务端地址绑定 SOCKADDR_IN serverAddr; int port = 5150; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); if (bind(listeningSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) { printf("bind failed with error %d\n", WSAGetLastError()); closesocket(listeningSocket); WSACleanup(); return; } //4:开启监听 if (listen(listeningSocket, 5) == SOCKET_ERROR) { printf("listen failed with error %d\n", WSAGetLastError()); closesocket(listeningSocket); WSACleanup(); return; } printf("We are waiting a connection on port %d\n", port); printf("Listening(我正在监听......)\n"); // NOLINT(clang-diagnostic-invalid-source-encoding) //5:接收客户端的连接请求 SOCKADDR_IN clientAddr; int clientAddrLen; SOCKET clientNewConnection; clientAddrLen = sizeof(SOCKADDR); if ((clientNewConnection = accept(listeningSocket, (sockaddr*)&clientAddr, &clientAddrLen)) == INVALID_SOCKET) { printf("accept failed with error %d\n", WSAGetLastError()); closesocket(listeningSocket); WSACleanup(); return; } //6:打印客户端套件字 //printf("we successfully got a connection from %s:%d\n", inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port)); closesocket(listeningSocket); //7:服务器接受客户端套件字 printf("we are waiting to receive data \n"); char dataBuffer[1024]; if ((ret = recv(clientNewConnection, dataBuffer, sizeof(dataBuffer), 0)) == SOCKET_ERROR) { printf("receive failed with error %d\n", WSAGetLastError()); closesocket(clientNewConnection); WSACleanup(); return; } printf("we successfully received %d bytes. \n", ret); dataBuffer[ret] = '\0'; printf("%s\n", dataBuffer); //8:关闭连接 printf("we are now going to close the client connection.\n"); closesocket(clientNewConnection); WSACleanup(); system("pause"); }