谁帮我写个简单c语言socket拜托各位大神

2024-12-04 18:32:50
推荐回答(1个)
回答(1):

////////////////////////////////////////////////////////// // initsock.h文件 #include #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData) != 0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; #include "../common/InitSock.h" #include CInitSock initSock; // 初始化Winsock库 int main() { // 创建套节字 SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sListen == INVALID_SOCKET) { printf("Failed socket() \n"); return 0; } // 填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8088); sin.sin_addr.S_un.S_addr = INADDR_ANY; // 绑定这个套节字到一个本地地址 if(::bind(sListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind() \n"); return 0; } // 进入监听模式 if(::listen(sListen, 2) == SOCKET_ERROR) { printf("Failed listen() \n"); return 0; } // 循环接受客户的连接请求 sockaddr_in remoteAddr; int nAddrLen = sizeof(remoteAddr); SOCKET sClient; //char szText[] = " TCP Server Demo! \r\n"; while(TRUE) { // 接受一个新连接 sClient = ::accept(sListen, (SOCKADDR*)&remoteAddr, &nAddrLen); if(sClient == INVALID_SOCKET) { printf("Failed accept()"); continue; } printf(" 接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr)); ::send(sClient,sendToFlex,sizeof(sendToFlex),0); // 向客户端发送数据 //// 关闭同客户端的连接 ::closesocket(sClient); } // 关闭监听套节字 ::closesocket(sListen); return 0; }