This is a server-side class that uses TCP transmission server client socket () bind () slisten () socket () accept () blocking. Waiting for customer connection () r () Write () processing service request write () Read () Close () Close ()
/ ************************************************** ******* 2004 12 06 Stephen ******************************************************* ***************** / # include
#define maxSize 50
#define WM_RecEiVedata WM_USER 1002
CLASS CNETSERVER {public: CNetServer (); CNetServer (int port); ~ CNETSERVER (); // read data static dword WinAPI ThreadServer (LPVOID N); // Initializing Server BOOL INITNETSERVER (); // Send to the specified client Bool SendDataToclient (int Nclient, char * data, int LEN); // Send to all client Bool SendDataToclient (Char * DATA, INT LEN); // Specify window handle of the received data {m_hwnd = hWnd;} int getCount (); // Return Error message char * getLastError (); // Turn off the server void closeServer (); // Turn off the server void destoryserver ();
PRIVATE: HANDLE HTHREAD;
HWND M_HWND;
Int port;
Char Szerror [256]; CHAR GETDATA [256]; int NRECEIVE; int Add add1;
Socket Sock; Socket Clientsocket [MaxSize]; SockAddr_in Servaddr;
WSADATA WSDATA;}; cnetServer :: CNetServer () {this-> Sock = invalid_socket; this-> hthread = null; this-> port = 9999; for (int i = 0; i
This-> servaddr.sin_addr.s_addr = htonl (inaddr_any); this-> servaddr.sin_family = af_INET; this-> servaddr.sin_port = htons (this-> port); this-> addlen = sizeof (servaddr);
SOCK = Socket (AF_INET, SOCK_STREAM, 0); if (SOCK == Socket_ERROR) {WSPrintf (this-> szerror, text ("Bind Failed.Error:% D"), wsagetlasterror ()); Return False;} IF Bind (Sock, (SockAddr *) & servaddr, sizeof (servaddr)) == SOCKET_ERROR) {WSPRINTF (this-> szerror, text ("Bind Failed.Error:% D"), wsagetlasterror (); return false;} else {Listen (Sock, 5); hthread = CREATTHREAD (NULL, 0, CNETSERVER :: Thread Server, this, 0, null; Return True;
}}} INT CNETSERVER :: getCount () {for (int i = 0; i
While (REV! = Socket_ERROR) {REV = Recv (PServer-> ClientSocket [Clientcount], BUFF, 1024, 0); if (REV! = Socket_ERROR) {// :: SendMessage (pserver-> m_hwnd, wm_receivedata, 0, (LParam); MessageBox (NULL, (LPCTSTSTSTSTST) BUFF, "ReceiveData", 0);}}}} Return 1;
bool CNetServer :: SendDataToClient (int nclient, char * data, int len) {int i = 0; if (sock == INVALID_SOCKET) return false; if (clientSocket [nclient] == INVALID_SOCKET) return false; if (send (clientSocket [NClient], DATA, LEN, 0) {WSPRINTF (this-> Szerror, Text ("Send Failed.Error:% D"), wsagetlasterror ()); Return False;} Return true;}