/****************************************************************/
/* */
/* LISTSOCKET.CPP */
/* */
/* Implementation of the Listen Socket. */
/* The server listens for connections. When a new connection */
/* is requested, the server accepts the connection and then */
/* creates a connect thread to handle the connection. */
/* */
/* Programmed by Pablo van der Meer */
/* Copyright Pablo Software Solutions 2002 */
/* http://www.pablovandermeer.nl */
/* */
/* Last updated: 10 july 2002 */
/* */
/****************************************************************/
//在ListenSocket.cpp文件中實現偵聽套接字的創建,該類用來偵聽連接請求,
//當一個新的連接被請求,服務器將接受這個這個請求并為其創建一個連接線程用來處理此連接
#include "stdafx.h"
#include "FTPServerApp.h"
#include "FTPServer.h"
#include "ApplicationDlg.h"
#include "ListenSocket.h"
#include "ConnectThread.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CListenSocket::CListenSocket()
{
m_pWndServer = NULL;
}
CListenSocket::~CListenSocket()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CListenSocket, CAsyncSocket)
//{{AFX_MSG_MAP(CListenSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/********************************************************************/
/* */
/* Function name : OnAccept */
/* Description : Called by the framework to notify this listening */
/* socket that it can accept pending connection */
/* requests by calling the Accept member function. */
/* */
/********************************************************************/
//接受等待的請求連接
void CListenSocket::OnAccept(int nErrorCode)
{
// 新的連接建立
CSocket sockit;
// 用一個臨時的CSocket對象接收連接
Accept(sockit);
// 創建一個新的線程來處理連接
CConnectThread* pThread = (CConnectThread*)AfxBeginThread(RUNTIME_CLASS(CConnectThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
if (!pThread)
{
sockit.Close();
TRACE("Could not create thread\n");
return;
}
CFTPServer *pWnd = (CFTPServer *)m_pWndServer;
// 添加這個線程到列表中
pWnd->m_CriticalSection.Lock();
pWnd->m_ThreadList.AddTail(pThread);
pWnd->m_CriticalSection.Unlock();
// 保存指針
pThread->m_pWndServer = m_pWndServer;
// 把套接字句柄傳送給這個線程
pThread->m_hSocket = sockit.Detach();
// 啟動線程
pThread->ResumeThread();
CAsyncSocket::OnAccept(nErrorCode);
}