// MySocket.cpp : implementation file
//

#include "stdafx.h"
#include "FileTransferServer.h"
#include "MySocket.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMySocket
CMySocket::CMySocket():Thdidx(0)
{
}

CMySocket::~CMySocket()
{
}


// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CMySocket, CAsyncSocket)
    //{{AFX_MSG_MAP(CMySocket)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif    // 0

/////////////////////////////////////////////////////////////////////////////
// CMySocket member functions
//OnAccept重载函数
void CMySocket::OnAccept(int nErrorCode) 
{
    // TODO: Add your specialized code here and/or call the base class
    static int File_Socket_Accepted=0;
    //接受套接字连接
    if(!listenSocket.Accept(sendSockets[File_Socket_Accepted]))
    {
        AfxMessageBox("Connect fail");
        return;
    }
    sendSockets[File_Socket_Accepted].AsyncSelect(FD_READ|FD_WRITE|FD_CLOSE);
    Thdidx=++File_Socket_Accepted;
    if(File_Socket_Accepted==NumOfThread)
    {
        AfxMessageBox("Connect success");
        listenSocket.Close();
    }
    CAsyncSocket::OnAccept(nErrorCode);
}
//OnSend重载函数
void CMySocket::OnSend(int nErrorCode)
{
    // TODO: Add your specialized code here and/or call the base class
    //设置文件发送事件对象,通知线程可以发送数据
    SetEvent(hMessageSend[Thdidx-1]);
    CAsyncSocket::OnSend(nErrorCode);
}



//ThreadFunc.cpp

//发送数据线程
DWORD WINAPI SendThreadFunction(void * pParam)
{
    int idx=(int)pParam;
    //调用发送文件函数
    SendThread(idx+1);
    return 1;
}
//发送数据函数
void SendThread(int idx)
{
    //定义一些变量
    CFile file;
    char data[ReadSize];
    //文件起始位和文件块大小
    long BeginPos,Size;
    long FileLength;
    long ReadOnce,LeftToRead,count;
    //以共享和读方式打开文件
    if(!file.Open(fn,CFile::modeRead|CFile::shareDenyNone))
    {
        AfxMessageBox("Read file error");
        return;
    }
    FileLength=(long)file.GetLength();
    sendSockets[idx-1].Send(&FileLength,4);
    WaitForSingleObject(hMessageSend[idx-1],2000);
    sendSockets[idx-1].Send(fn,40);
    //获得文件起始位和文件块大小
    GetBeginPos(NumOfThread,idx,FileLength,BeginPos,Size);
    //定位到文件开始位
    file.Seek(BeginPos,CFile::begin);
    LeftToRead=Size;
    //读取文件并发送文件块
    while(LeftToRead>0)
    {
        ReadOnce=(LeftToRead>ReadSize?ReadSize:LeftToRead);
        count=file.Read(data,ReadOnce);
        WaitForSingleObject(hMessageSend[idx-1],20);
        //发送文件块
        while((SOCKET_ERROR==sendSockets[idx-1].Send(data,count)))
        {
        }
        LeftToRead=LeftToRead-count;
    }
    
    
    这个函数在程序里面是不是没作用?WaitForSingleObject(hMessageSend[idx-1],2000);
hMessageSend[idx-1],这个事件只在接受连接的时候被设置了一次,其他的地方都没有看到有设置,是不是在程序里可有可无?