/ / The following is a server-side SDK code, simpler, slightly modified can be applied to the NT service program // For beginners reference, expert, thank you #pragma Warning (Disable: 4530) #pragma Warning (disable: 4786) #include
#include
#include "thread.h" // This file is seen from the end of this article #include "threadpool.h" // see my Win32 thread pool article
char * GetErrorMessage (char * szBuffer, DWORD dwSize) {FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language szBuffer, dwSize - 1, NULL); return szBuffer;}
class RFC868TCPServer: public ThreadJob, public Thread {SOCKET _S37; long _lWorkCount; bool _fRunFlag; u_long _uIP; ThreadPool _TP; public: RFC868TCPServer (DWORD tp_num = 10): _TP (tp_num), _S37 (INVALID_SOCKET), _lWorkCount (0), _fRunFlag (True) {_UIP = HTONL (INADDR_Any); // Default listening IP is local} ~ RFC868TCPServer () {if (_s37! = invalid_socket) clossoSocket (_S37);} BOOL Begin () // Start listening and start thread {char Buffer [256]; Struct SockAddr_in Server; Server.SIN_FAMILY = AF_INET; Server.sin_Port = HTONS (37); Server.sin_Addr.s_addr = _UIP;
IF ((_ S37 = socket (AF_INET, SOCK_STREAM, 0) == Invalid_socket) Return False;
Unsigned long Nonblock = 1; IF (ioctlsocket (_s37, fionbio, & nonblock == Socket_ERROR) RETURN FALSE
IF (Bind (_S37, (Struct SockAddr *) & Server, SIZEOF (Server)) == Socket_ERROR) RETURN FALSE
IF (Listen (_S37, 20) == Socket_ERROR) RETURN FALSE; return thread :: begin ();} inline bool end () {_frunflag = false; sleeep (100); return thread :: end ();} inline Bool Waitend (dWord dwaittime = infinite) {_frunflag = false; return! Wait (DWWAITTIME)? Thread :: end (): true;} Virtual void dojob (virt * para) 作 作 作 作 作 作 {{(socket s = * (Socket) *) Para; delete para; time_t cur_time = time (null) 2208988800; CHAR S_BUF [4], * TP = ((char *) & cur_time) 3; for (int i = 0; i <4; i ) s_buf [i] = * TP -;
IF (SEND (S, S_BUF, 4, 0) == Socket_ERROR) {LOGERROR (); ClosSocket (s); Return;}
if (shutdown (s, SD_SEND) == SOCKET_ERROR) {LogError (); closesocket (s); return;} closesocket (s); InterlockedIncrement (& _ lWorkCount);} inline void LogMessage (char * szStr) {Thread :: Lock ( COUT << Szstr << Endl; thread :: unlock ();} inline void logerror () {Char Buffer [256]; LogMessage (Buffer, 256));} inline long getcount ()}}}}} } Inline void setip (char * szipstr) {_UIP = inet_addr (szipstr);} inline void setip (u_long ip) {_UIP = IP;} Virtual void WorkProc () {Char Buffer [500]; socket ns, s = _s37;
Struct SockAddr_in Client; Int Len = SizeOf (Client), Ret;
FD_set read_set; TimeVal TV = {0, 100000}; ///tv.tv_sec = 0, TV.tv_usec = 100000;
While (_frunflag) {fd_zero (& read_set); fd_set (s, & oo);
RET = SELECT (0, & Read_set, Null, Null, & TV); // Selet Model
IF (RET == Socket_ERROR) {logMessage (GetErrorMessage (Buffer, 500)); Continue;}
IF (fd_isset (s, & read_set) // Wait until the client {ns = accept (s, (struct socmeddr *) & client, & len; if (ns! = invalid_socket) {_tp.call (this, New Socket (NS) ); // call the thread pool Sprintf (Buffer, "Accept Client% S (% D) / N", INT_NTOA (Client.sin_ADDR), NTOHS (Client.sin_Port)); LogMessage (Buffer);} else logmessage (GetErrorMessage Buffer, 500));}} _tp.endandwait ();}};
int main (int argc, char * argv []) {try {char Buffer [256]; WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD (2, 2); if (WSAStartup (wVersionRequested, & wsaData)) {cout << __LINE__ << getErrorMessage (Buffer, 256) << Endl; Return 1;} RFC868TCPSERVER TCP; if (! Tcp.begin ()) cout << __line__ << getErrorMessage (Buffer, 256) << endl; for (;;) { Sleep (200); if (tcp.getWorkcount ()> = 5) // Exit Break;} tcp.waitend (); wsacleanup ();} catch (exception & e) {cout << E .what () << Endl;} return 0;} // ----------------------------------- ------- Thread.h ------------------------------------------------------------------------------------ --------- # iFNDef_thread_h_ # define _thread_h_
#include
class Thread {typedef DWORD WINAPI ThreadProcType (LPVOID lpPara); static DWORD WINAPI DefaultThreadProc (LPVOID lpPara) {Thread * pThis = (Thread *) lpPara; pThis-> WorkProc (); return 0;} CRITICAL_SECTION _csBaseThreadLock; protected:
Virtual void WorkProc ()}
Handle _hthreadhandle; dword _dwthreadid;
public: Thread () {_hThreadHandle = NULL; InitializeCriticalSection (& _ csBaseThreadLock);} ~ Thread () {DeleteCriticalSection (& _ csBaseThreadLock); if (_ hThreadHandle!) CloseHandle (_hThreadHandle);} Thread (Thread &) {_hThreadHandle = NULL;} Thread & operator = (Thread & x) {return * this;} bool IsRunning () {return _hThreadHandle = NULL;!} void Lock () {EnterCriticalSection (& _ csBaseThreadLock);} void UnLock () {LeaveCriticalSection (& _ csBaseThreadLock);} inline bool Begin (ThreadProcType ThreadProc = DefaultThreadProc) {if) _hThreadHandle = CreateThread (NULL, 0, ThreadProc, this, 0, & _dwThreadID) (IsRunning (!); return IsRunning ();};! inline bool Begin (ThreadProcType ThreadProc, LPVOID lpPara) {if (IsRunning ()) _HthreadHandle = CreateThread (Null, 0, ThreadProc, LPpara, 0, & _dwthread);
return IsRunning ();}; inline bool End (DWORD dwEndCode = 0) {if (IsRunning ()) {if (! TerminateThread (_hThreadHandle, dwEndCode)) return false; else {CloseHandle (_hThreadHandle); _hThreadHandle = NULL; return true ;}} return false;} inline virtual bool Wait (DWORD dwWaitTime = INFINITE) {return IsRunning () WaitForSingleObject (_hThreadHandle, dwWaitTime) == WAIT_OBJECT_0:?? false;} inline bool Suspend () {return IsRunning () SuspendThread (_hThreadHandle ) = 0xFFFFFFFF:! false;} inline bool Resume () {return IsRunning () ResumeThread (_hThreadHandle) = 0xFFFFFFFF:?! false;} inline int getPriority () {assert (IsRunning ()); return GetThreadPriority (_hThreadHandle);} inline bool SetPriority (int iPriority) {assert (IsRunning ()); return SetThreadPriority (_hThreadHandle, iPriority);} inline const HANDLE GetThreadHandle () {return _hThreadHandle;} inline const DWORD getThreadID () {return _dwThreadID;}}; #endif // _ three_h_