本文主要是介绍Select模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
服务端:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <windows.h>int main()
{WSADATA lpWSAData;WSAStartup(MAKEWORD(2, 2), &lpWSAData);SOCKADDR_IN saddr{ 0 };saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");saddr.sin_family = AF_INET;saddr.sin_port = htons(50123);SOCKET SerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);bind(SerSocket, (PSOCKADDR)&saddr, sizeof(saddr));listen(SerSocket, SOMAXCONN);fd_set all_Sockets{ 0 };FD_SET(SerSocket, &all_Sockets);while (true){fd_set fdRead = all_Sockets;int sRet = select(NULL, &fdRead, NULL, NULL, NULL);if (sRet > 0){for (size_t i = 0; i < all_Sockets.fd_count; i++){if (FD_ISSET(all_Sockets.fd_array[i], &fdRead)){if (fdRead.fd_array[i] == SerSocket){if (fdRead.fd_count < FD_SETSIZE){SOCKADDR_IN temp{ 0 };int length = sizeof(SOCKADDR_IN);SOCKET NewSocket = accept(SerSocket, (PSOCKADDR)&temp, &length);FD_SET(NewSocket, &all_Sockets);printf("IP:%s\t", inet_ntoa(temp.sin_addr));char buff[MAXBYTE]{ 0 };sprintf(buff, "%d", ntohs(temp.sin_port));printf("Port:%s\n",buff);}else{printf("Clients too much!");}}else{char buffer[0x500]{0};sRet = recv(fdRead.fd_array[i], buffer, sizeof(buffer), 0);if (sRet > 0){std::cout << buffer << std::endl;}else{closesocket(fdRead.fd_array[i]);FD_CLR(fdRead.fd_array[i], &all_Sockets);}}}}}}shutdown(SerSocket, SD_BOTH);WSACleanup();system("pause");return 0;
}
客户端:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <windows.h>int main()
{WSADATA lpWSAData;WSAStartup(MAKEWORD(2, 2), &lpWSAData);SOCKADDR_IN caddr{ 0 };caddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");caddr.sin_family = AF_INET;caddr.sin_port = htons(50123);SOCKET CliSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);int iMode = 1;ioctlsocket(CliSocket, FIONBIO, (u_long*)&iMode);while (true){int Ret = connect(CliSocket, (PSOCKADDR)&caddr, sizeof(caddr));if (Ret == SOCKET_ERROR){int nError = WSAGetLastError();if (nError == WSAEWOULDBLOCK || nError == WSAEINVAL){Sleep(1);printf("check connect!\r\n");continue;}else if (nError == WSAEISCONN){break;}else{printf("connect failed!\r\n");closesocket(CliSocket);WSACleanup();return 0;}}}while (true){printf("\r\ninput you send buffer:\r\n");char str[256]{ 0 };std::cin >> str;while (true){int Ret = send(CliSocket, str, strlen(str), 0);if (Ret == SOCKET_ERROR){int nError = WSAGetLastError();if (nError == WSAEWOULDBLOCK){Sleep(1);continue;}else{printf("send failed!\r\n");closesocket(CliSocket);WSACleanup();return 0;}}break;}}system("pause");return 0;
}
这篇关于Select模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!