/* 功能:客户端函数,发起TCP连接 参数: lpszHostAddress LPCTSTR [In] 对方Ip地址或域名 nHostPort UINT [In] 对方监听的端口 返回值:成功返回TRUE,失败返回FALSE */ bool Socket::Connect( const char *lpszHostAddress, unsigned short nHostPort, long lSecond ) { if ( NULL == lpszHostAddress ) return false; //将域名转换为真实IP,如果lpszHostAddress本来就是ip,不影响转换结果 char ip[64]; //真实IP #ifdef WIN32 PHOSTENT hostinfo; #else struct hostent * hostinfo; #endif strcpy( ip, lpszHostAddress ); if((hostinfo = gethostbyname(lpszHostAddress)) != NULL) { strcpy( ip, inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list) ); } //使用真实ip进行连接 sockaddr_in sockAddr; memset(&sockAddr,0,sizeof(sockAddr)); sockAddr.sin_family = AF_INET; sockAddr.sin_addr.s_addr = inet_addr(ip); sockAddr.sin_port = htons( nHostPort ); SetSendTimeout(lSecond, 0); if ( SOCKET_ERROR != connect(m_hSocket, (sockaddr*)&sockAddr, sizeof(sockAddr)) ) { SetSendTimeout(0, 0); InitPeerAddress(); InitLocalAddress(); return true; } SetSendTimeout(0, 0); return false; }
void Server::Run() { serverSocket.Listen(maxConnections); std::cout << "Server now listening for incoming connections at port " << serverSocket.GetPort() << '\n'; threadPool.Startup(); running = true; while(running) { if(serverSocket.IsReady()) { try { auto clientSocketPtr = std::make_shared<Socket>(serverSocket.Accept()); threadPool.EnqueueTask([this, clientSocketPtr]() mutable { clientSocketPtr->SetReceiveTimeout(1); clientSocketPtr->SetSendTimeout(1); this->ServeClient(*clientSocketPtr); }); } catch(const SystemException& e) { std::lock_guard<std::mutex> guard(stderrMutex); std::cerr << e.what() << '\n'; } } } }
void TCPClient::Init() { CreateTCPSocket(); SetReceiveTimeout(this->_tcp_socket); SetSendTimeout(this->_tcp_socket); Connect(); cout << "Connected to " << this->address << ":" << this->port << endl; }
Server::Server(unsigned int port) { this->port = port; _udp_socket = CreateUDPSocket(); CreateTCPSocket(); Bind(_udp_socket); Bind(this->_tcp_socket); SetSendTimeout(this->_tcp_socket); SetReceiveTimeout(_udp_socket, GetTimeout(100)); Listen(); FD_ZERO(&this->clientsSet); FD_ZERO(&this->serverSet); FD_SET(this->_tcp_socket, &this->serverSet); FD_SET(_udp_socket, &this->serverSet); std::cout << "Server started at port: " << this->port << std::endl; }