⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tsthread.cpp

📁 nucleus source 源码 全部源码
💻 CPP
字号:
// TSThread.cpp : implementation file
//

/****************************************************************************/
/* FILE         				    										*/
/*																			*/
/* TSThread.cpp                                                             */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Contains routines Necessary to run the Winsock TCP Server application.   */
/*																			*/
/****************************************************************************/

#include "stdafx.h"
#include "nunetdem.h"
#include "NuNetDemDlg.h"
#include "TSThread.h"
#include "winsock.h"
#include "SockUtil.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CTcpServerThread

//IMPLEMENT_DYNCREATE(CTcpServerThread, CWinThread)
IMPLEMENT_DYNAMIC(CTcpServerThread, CWinThread)


/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::CTcpServerThread                                       */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Starts the TCP Server Thread.                                            */ 
/*																			*/
/****************************************************************************/

CTcpServerThread::CTcpServerThread(CNuNetDemDlg * pWnd)
{
	pDlgWnd = pWnd;

	// kill event starts out in the signaled state
	m_hEventKill = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_hEventDead = CreateEvent(NULL, TRUE, FALSE, NULL);

}

/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::~CTcpServerThread                                      */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Ends the TCP Server Thread.                                              */
/*																			*/
/****************************************************************************/

CTcpServerThread::~CTcpServerThread()
{
	CloseHandle(m_hEventKill);
	CloseHandle(m_hEventDead);

}

/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::InitInstance                                           */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Perform Thread Initialization.                                           */
/*																			*/
/****************************************************************************/

BOOL CTcpServerThread::InitInstance()
{
	// TODO:  perform and per-thread initialization here
	

	// Initialize
	CNuNetDemDlg::c_lBytesTCPServe = 0;
	UpdateByteCount();

	// avoid entering standard message loop by returning FALSE
	return FALSE;
}

/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::ExitInstance                                           */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Performs any thread clean-up.                                            */
/*																			*/
/****************************************************************************/

int CTcpServerThread::ExitInstance()
{
	// TODO:  perform any per-thread cleanup here

	//AfxMessageBox("TCP Server Thread Stopped");

	return CWinThread::ExitInstance();
}

/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::Delete                                                 */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Deletes the Thread.                                                      */
/*																			*/
/****************************************************************************/

void CTcpServerThread::Delete()
{
	// acknowledge receipt of kill notification
	SetEvent(m_hEventDead);

	// calling the base Delete
	CWinThread::Delete();

}



/****************************************************************************/
/* FUNCTION         														*/
/*																			*/
/* CTcpServerThread::KillThread                                             */    
/*																			*/
/* DESCRIPTION																*/
/*																			*/
/* Kills the Thread.(Shuts it down.)                                        */
/*																			*/
/****************************************************************************/

void CTcpServerThread::KillThread()
{

	// Reset the m_hEventKill which signals the thread to shutdown
	SetEvent(m_hEventKill);

	// Allow thread to run at higher priority during kill process
	SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
	WaitForSingleObject(m_hEventDead, INFINITE);
	
}


BEGIN_MESSAGE_MAP(CTcpServerThread, CWinThread)
	//{{AFX_MSG_MAP(CTcpServerThread)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTcpServerThread message handlers

/*************************************************************************/
/*                                                                       */
/* FUNCTION                                                              */
/*                                                                       */
/*  CTcpServerThread::UpdateByteCount                                    */
/*                                                                       */
/*                                                                       */
/* DESCRIPTION                                                           */
/*                                                                       */
/*      This function listens for and accepts connections from clients.  */
/*                                                                       */
/*************************************************************************/
#define RECEIVE_SIZE    2000
#define  NU_SUCCESS   0

int CTcpServerThread::UpdateByteCount()
{

    int					socketd;				/* the socket descriptor */
    struct sockaddr_in  *servaddr;              /* holds the server address structure */
    VOID                *pointer;
    int                 status;
    struct sockaddr_in  client_addr;
	int					connected = 1;
	int					bytes_recv;
	int					newsock;

	unsigned long		Total_Bytes_Received;
	unsigned long		Total_Packets_Received;
	char				line[RECEIVE_SIZE];
	typedef int			STATUS;
	typedef unsigned int   UNSIGNED;
	WSADATA				WsaData;
	CString				sNumBytes;
	int port=			pDlgWnd->m_Port;		/* number of port to use */
	CString				sStatus;
	CSockUtil			sockUtil;				/* WinSock Error Messages */


    /*  Intialize global counters.  */
    Total_Bytes_Received = 0;
    Total_Packets_Received = 0;

	// Initialize Windows Sockets and request version 1.1
	status = WSAStartup (0x0101, &WsaData);
	if (status == SOCKET_ERROR)
	{
		AfxMessageBox("WSAStartup() failed");
		return(1);
   }

	// Stay in this Thread until the application ends
	while (1)
	{

		// Open a connection via the socket interface 
		if ((socketd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) != INVALID_SOCKET )
		{

			//  Allocate space for the buffer.
			pointer = (void *)malloc(sizeof(struct sockaddr_in));

			if (pointer != NULL)
			{
				servaddr = (struct sockaddr_in *)pointer;

				// Fill in a structure with the server address
				servaddr->sin_family    = AF_INET;
				servaddr->sin_port      = htons(port);
				servaddr->sin_addr.s_addr = htons(INADDR_ANY);

				// Make an NU_Bind() call to bind the server's address 
				if ((status = bind(socketd, (struct sockaddr *)servaddr, sizeof(struct sockaddr_in)))>=0)
				{

					/* be ready to accept connection requests */
					status = listen(socketd, 10);

					if (status == 0)
					{
						int nbyte = sizeof(client_addr);

						//AfxMessageBox("listen is successfull\n");
                      while(1)
                      {
                                  Total_Packets_Received=0;
                                  Total_Bytes_Received=0;
						/* block in NU_Accept until a client attempts connection */
						newsock = accept(socketd, (struct sockaddr *)&client_addr, &nbyte);
						if (newsock >= 0)
						{
							// Wait for thread event
							while (WaitForSingleObject(m_hEventKill, 0) != WAIT_OBJECT_0 )
							{
								// Wait to receive a string buffer
								bytes_recv = recv(newsock, line, RECEIVE_SIZE, 0);

								// Check for Errors
								if ((bytes_recv == SOCKET_ERROR) || (bytes_recv == 0))
								{
									if (bytes_recv == SOCKET_ERROR)
									{
										sStatus.Format("Receive error - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
										AfxMessageBox(sStatus);			   
									}
									if (bytes_recv == 0)
										AfxMessageBox("Connection has closed. No bytes received.\n");

									connected = 0;
									break;
								}
								else
								{
									// We have a good buffer of data. NULL terminate the buffer
									line[bytes_recv] = '\0';

									// Update total bytes and packets received
									Total_Bytes_Received += bytes_recv;
									
									// Show Total Bytes Received
									CNuNetDemDlg::c_lBytesTCPServe = Total_Bytes_Received;
									sNumBytes.Format("%u",Total_Bytes_Received);
									pDlgWnd->m_edBytesTCPServe.SetWindowText(sNumBytes);
                                  
                                    sNumBytes.Format("%u",Total_Packets_Received + 1);
                                    pDlgWnd->m_edpcktTCPSERVE.SetWindowText(sNumBytes);

									// Show the string Received
									pDlgWnd->UpdateList(line, Total_Packets_Received + 1, bytes_recv);                       

                                    Total_Packets_Received++;

								}

								// Send Back the line received.
								if (send(newsock, line, bytes_recv, 0) != bytes_recv)
									;//printf("\nstr_echo: send error\n");


                          
							}

							
                        

						} // End successful: Accept

						else // Error !!!
						{
							AfxMessageBox("Error in Accept: Can't accept. newsock");
						}

                        // Close the New connection
                		if ((closesocket(newsock)) != NU_SUCCESS)
                        {
			                     sStatus.Format("Problem closing New socket! - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
			                     AfxMessageBox(sStatus);
                        }

                      } /* end while 1 */
					} /* end successful NU_Listen */

					else // Error !!!
					{
						sStatus.Format("Can't Listen - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
						AfxMessageBox(sStatus);			   
					}
				} /* end successful NU_Bind */

				else // Error !!!
				{
					sStatus.Format("Cant't bind - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
					AfxMessageBox(sStatus);			   
				}

			} // End successful memory allocation 

		} // End successful NU_Socket */

		else // Error !!!
		{
			sStatus.Format("Can't socket - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
			AfxMessageBox(sStatus);			   
		}


		// Close the connection
		if ((closesocket(socketd)) != NU_SUCCESS)
		{
			sStatus.Format("Problem closing socket! - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
			AfxMessageBox(sStatus);
		}

		// Close the New connection
		if ((closesocket(newsock)) != NU_SUCCESS)
		{
			sStatus.Format("Problem closing New socket! - %s\n",sockUtil.SockerrToString(WSAGetLastError() ) );
			AfxMessageBox(sStatus);
		}

	} // End While

	// De-register WinSock
    WSACleanup();                        

	free(pointer);

	return (0);

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -