Blocking socket class-CPP file

xiaoxiao2021-03-06  44

// mysocket.cpp: importation of the cmysocket class.//// -------------------------------- - // * Program Name: MySocket.h // * Package Name: Network Socket Package // * Function: Packaging Network Address // * Dependent Components: Two Classs in MySocket.h // * Author: FUSX // * Development Date: 2003/06/11 // * Modification Date: 2004/06/06 // * Project Name: // * Discount: // --------- ---------------------------

#include "stdafx.h" #include "mysocket.h" #include #include

#ifdef _debug # undef this_filestatic char this_file [] = __ file __; # Define new debug_new # Endif

//// construction / destruction //

CMYSOCKET :: CMYSocket (): m_hsocket (invalid_socket), m_nerrcode (0) {}

CMYSOCKET :: ~ cmysocket () {assert (m_hsocket == invalid_socket); wsacleanup ();}

Void CMYSOCKET :: Operator = (Socket SCK) {Assert (m_hsocket == invalid_socket); m_hsocket = SCK;} // Create a socket BOOL CMYSOCKET :: Create (int NTYPE) {askET (m_hsocket == invalid_socket);

WSADATA wsaData; if (WSAStartup (MAKEWORD (2, 2), & wsaData)) {m_nErrCode = WSAGetLastError (); return false;} if ((m_hSocket = socket (AF_INET, nType, 0)) == INVALID_SOCKET) {m_nErrCode = WSAGetLastError (); Return false;} return true;

// bind a socket bool CMySocket :: Bind (LPCSOCKADDR psa) {assert (m_hSocket = INVALID_SOCKET!); If (bind (m_hSocket, psa, sizeof (SOCKADDR)) == SOCKET_ERROR) {m_nErrCode = WSAGetLastError (); return False;} Return True;} // Listening Socket Bool CMYSOCKET :: Listen () {assert (m_hsocket! = invalid_socket);

IF (Listen (M_HSocket, 5) == Socket_ERROR) {m_nerrcode = wsagetlasterror (); return false;} Return true;}

// Connect the server BOOL CMYSOCKET :: Connect (LPCSOCKADDR PSA) {assert (m_hsocket! = Invalid_socket);

// Should Timeout by Itselfix (Connect (M_HSocket, PSA, SIZEOF (SOCKADDR)) == Socket_ERROR) {m_nerrcode = wsagetlasterror (); Return false;} Return true;}

Receiving socket // bool CMySocket :: Accept (CMySocket & sConnect, LPSOCKADDR psa, int nSecs) {assert (m_hSocket = INVALID_SOCKET!); Assert (sConnect.m_hSocket == INVALID_SOCKET); // Set the timeout if (nSecs = 0! ) {Fd_set fd = {1, m_hsocket}; TimeVal TV = {nsecs, 0}; if (SELECT (0, & FD, NULL, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; returnaf}}}

// receiving connector socket int nLengthAddr = sizeof (SOCKADDR); sConnect.m_hSocket = accept (m_hSocket, psa, & nLengthAddr); if (sConnect == INVALID_SOCKET) {m_nErrCode = WSAGetLastError (); return false;} return true;}

// Send data, the return value is the data byte sent out, not necessarily all data BOOL CMYSOCKET:: Send (const char * pch, const nSize, int ") {assert (m_hsocket! = Invalid_socket);

// If the client cancels the read data, the return value is less than nsize fd_set fd = {1, m_hsocket}; TimeVal TV = {nsecs, 0}; if (SELECT (0, NULL, & FD, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; return false;} // if ((Nbytessent = send (m_hsocket, pch, nsize, 0) == Socket_ERROR) {m_nerrcode = wsagetlasterror (); return false;} return true;} // Send all specified data Bool CMYSocket :: Write (const char * pch, const Int nsize, int nsecs) {assert (m_hsocket! = Invalid_socket);

/ / Set the timeout value fd_set fd = {1, m_hsocket}; TimeVal TV = {nsecs, 0}; if (SELECT (0, NULL, & FD, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; returnaf

int nBytesSent = 0; int nBytesThisTime; const char * pch1 = pch; do {nBytesThisTime = send (m_hSocket, pch, nSize, 0); if (nBytesThisTime == SOCKET_ERROR) {m_nErrCode = WSAGetLastError (); return false;} nBytesSent = NBYTESTHISTIME; PCH1 = nbytesthistime;} while (nbytessent

// Accept the data from the other party, return bytes /// Note: If the socket is turned off, return the value of 0 characters Bool CMYSOCKET :: Receive (Char * PCH, Const Int Nsize, Int & nbytesReceived, int NSECS) {Assert (m_hsocket! = Invalid_socket);

// Set timeout fd_set fd = {1, m_hsocket}; TimeVal TV = {nsecs, 0}; if (SELECT (0, & FD, NULL, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; Return False;} / / nBytesReceived = recv (m_hSocket, pch, nSize, 0); if (nBytesReceived == SOCKET_ERROR) {m_nErrCode = WSAGetLastError (); return false;} return true;} / * bool CMySocket :: Read (char * pch, const int NSIZE, INT NBYTESREAD, INT NSECS) {Assert (m_hsocket! = invalid_socket);

FD_SET FD = {1, M_HSocket}; int NTIMEOUT, NLEFT = NBYTESREAD; Char * Ptemp = PCH; Do {IF ((nsecs == 0) && (nmillsecs == 0)) NTIMEOUT = SELECT (0, & fd, null, Null, null; else {timevalval TV = {nsecs, nmillsecs}; ntimeout = SELECT (0, & fd, null, null, & TV);} if (ntimeout == 0) {NERRCODE = wsagetlasterror (); return false;} // int nBytesReceived = recv (m_hSocket, pTemp, nLeft, 0); if (nBytesReceived == SOCKET_ERROR) {nErrCode = WSAGetLastError (); return false;} pTemp = nBytesReceived; nLeft - = nBytesReceived;} while (nLeft <= 0); return true;} * /// Accept the datagram, return accepted data bytes Bool CMYSocket :: ReceiveDataGram (LPSOCKADDR PSA, CHAR * PCH, Const Int NSIZE, INT & NBYTESRECEIVED, INT NSECS) {assert (m_hsocket! = INVALID_SOCKET); // Set timeout fd_set fd = {1, m_hsocket}; timeval TV = {nsecs, 0}; if (SELECT (0, NULL, & FD, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; return; Return False;} // Accepted cache space should be greater than all Data report INT nfromsize = sizeof (sockaddr); nbytesReceived = recvfrom (m_hsocket, pch, nsize, 0, psa, & nfromsize); i f (nbytesReceived == Socket_ERROR) {m_nerrcode = wsagetlasterror (); return false;} return true;}

// Send a datagram, return the number of bytes sent out, how many bool cmysocket :: SendDataGram (LPCSOCKADDR PSA, Const Char * PCH, Const Int NSIZE, INT & NBYTESSSSSSSSSSSst, Int nsecs) {assert (m_hsocket! = Invalid_socket); // Set timeout FD_SET FD = {1, M_HSocket}; TimeVal TV = {Nsecs, 0}; IF (SELECT (0, NULL, & FD, NULL, & TV) == 0) {m_nerrcode = wsaetimedout; return false;} // nbytessent = sendto (M_HSocket, PCH, NSIZE, 0, PSA, SIZEOF (SockAddr)); if (nbytessent == Socket_ERROR) {m_nerrcode = wsagetlasterror (); return false;} return true;} // Get the other party socket address BOOL CMYSOCKET :: GetPeerAddr (LPSOCKADDR psa) {assert (m_hSocket = INVALID_SOCKET!); // int nLengthAddr = sizeof (SOCKADDR); if (getpeername (m_hSocket, psa, & nLengthAddr) == SOCKET_ERROR) return false;

Return True;}

// Get the local socket address bool CMySocket :: GetSockAddr (LPSOCKADDR psa) {assert (m_hSocket = INVALID_SOCKET!); // int nLengthAddr = sizeof (SOCKADDR); if (getsockname (m_hSocket, psa, & nLengthAddr) == SOCKET_ERROR Return False;

Return True;}

// static function // Get the name of the host address CSockAddr CMySocket :: GetHostByName (const char * pchName, const USHORT ushPort / * = 0 * /) {SOCKADDR_IN sockTemp According; sockTemp.sin_family = AF_INET; sockTemp.sin_port = htons (ushPort) Socktemp.sin_addr.s_addr = 0;

Hostent * phostent = gethostByname (pchname); if (phostent! = null) {ulong * puladdr = (ulong *) phostent-> h_addr_list [0]; socktemp.sin_addr.s_addr = * puladdr; // address is already network byte Sequence} return socktemp;

// static function // Get the host name const char * CMYSOCKET :: gethdr psa) {hostent * phostent = gethostbyaddr ((char *) & ((lpsockaddr_in) PSA) -> sin_addr.s_addr, 4, pf_inet) ; If (phostent == null;} Return phostent-> h_name; // caller shopn't delete this memory} // static function // Get local computer IP and hostname Bool CMYSOCKET :: GetLocalhostInfo (LPTSTR Strhostname, LPTSTSTSTSTSTSTSTIP) {// Get host name. Char Hostname [256]; int res = gethostname (Hostname, Sizeof (Hostname)); if (res! = 0) Return False;

Strcpy (strHostname, Hostname);

// Get Host Info for hostname. Hostent * phostent = gethostByName (Hostname); if (phostent == null) Return False;

// Parse The Hostent Information Returned Hostent & He = * Phostent

SockAddr_in sa; memcpy (& sa.sin_addr.s_addr, he.h_addr_list [0], he.h_length);

// for (int Nadapter = 0; he.h_addr_list [nadapter]; Nadapter ) // {// Memcpy (& sa.sin_addr.s_addr, he.h_addr_list [nadapter], he.h_length); // // Output The Machines IP address. // // Trace ("Address:% S / N", INET_NTOA (Sa.sin_ADDR)); // Display As String ///} STRCPY (Strhostip, INT_NTOA (Sa.sin_ADDR));

Return True;}

// Close the socket Bool CMYSocket :: Close () {// If it is already closed, call this function will not be wrong. IF (invalid_socket == m_hsocket) Return True;

IF (CloseSocket (M_HSocket) == Socket_ERROR) {m_nerrcode = wsagetlasterror (); Return False;} m_hsocket = invalid_socket; returntrue;}

// Connect server bool CMySocket :: Connect (LPCTSTR strIP, int nPort) {assert (m_hSocket = INVALID_SOCKET!); // should timeout by itself CSockAddr sa (strIP, nPort); if (connect (m_hSocket, sa, sizeof (SOCKADDR )) == SOCKET_ERROR) {m_nerrcode = wsagetlasterror (); return false;} reburn true;} bool cmysocket :: bind (lpctstr strip, int nport) {assert (m_hsocket! = Invalid_socket);

CSOCKADDR SA (Strip, Nport); if (Bind (M_HSocket, SA, SIZEOF (SOCKADDR)) == Socket_ERROR) {m_nerrcode = wsagetlasterror (); return false;} return true;}

The system error code // Get error string bool CMySocket :: GetErrorMessage (const int nErrCode, char * pErrMsg, int nMaxLen) {assert (pErrMsg = NULL!); LPVOID lpMsgBuf; DWORD dwLen = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL, NERRCODE, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), / / ​​DEFAULT LANGUAGE (LPTSTSTSTS & LPMSGBUF, 0, NULL); if (dwlen == 0) {PerRMSG [0] = 0; Return False;} else {IF (Nmaxlen > (int) dwlen) nmaxlen = (int) dwlen; memcpy (perrmsg, lpmsgbuf, nmaxlen-1); perrmsg [nmaxlen-2] = 0; LocalFree (lpmsgbuf);} return true;}

转载请注明原文地址:https://www.9cbs.com/read-79297.html

New Post(0)