代码参考代码仓库.
功能为服务器端向多个客户端发送程序.仅供演示
服务器端
#include"Afxsock.h"
DWORD WINAPI ThreadFunc(LPVOID lpParam);
int flag;
CRITICAL_SECTION CriticalSection; void CSERVERDlg::OnButtonSend() 
{
 dwThrdParam = 1;
 flag=1;
 InitializeCriticalSection(&CriticalSection); hThread = CreateThread( 
        NULL,                        // no security attributes 
        0,                           // use default stack size  
        ThreadFunc,                  // thread function 
        &dwThrdParam,                // argument to thread function 
        0,                           // use default creation flags 
        &dwThreadId);                // returns the thread identifier 
/////////////
}DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
#define PORT 34000 /// Select any free port you wish AfxSocketInit(NULL);
 CSocket sockSrvr; 
 sockSrvr.Create(PORT); // Creates our server socket
 while(flag)
 {
 sockSrvr.Listen(); // Start listening for the client at PORT
  CSocket sockRecv;
 sockSrvr.Accept(sockRecv); // Use another CSocket to accept the connectionEnterCriticalSection(&CriticalSection); 
 CFile myFile;
 myFile.Open("C:\\cc.txt", CFile::modeRead | CFile::typeBinary);  int myFileLength = myFile.GetLength(); // Going to send the correct File Size sockRecv.Send(&myFileLength, 4); // 4 bytes long,整型变量4个字节

 byte* data = new byte[myFileLength];  myFile.Read(data, myFileLength); sockRecv.Send(data, myFileLength); //Send the whole thing now myFile.Close();
 LeaveCriticalSection(&CriticalSection); delete data;
  sockRecv.Close();
 }
 DeleteCriticalSection(&CriticalSection);
return 0;
}void CSERVERDlg::OnButtonStop() 
{
// TODO: Add your control notification handler code here
flag=0;
}
客户端#include"Afxsock.h"void CClientDlg::OnButtonReceive() 
{
// TODO: Add your control notification handler code here
#define PORT 34000 /// Select any free port you wish AfxSocketInit(NULL);
 CSocket sockClient;
 sockClient.Create(); // "127.0.0.1" is the IP to your server, same port
 sockClient.Connect("127.0.0.1", PORT);  int dataLength;
 sockClient.Receive(&dataLength, 4); //Now we get the File Size first

 byte* data = new byte[dataLength];
 sockClient.Receive(data, dataLength); //Get the whole thing CFile destFile("C:\\temp1\\z1.txt", 
  CFile::modeCreate | CFile::modeWrite | CFile::typeBinary); destFile.Write(data, dataLength); // Write it destFile.Close(); delete data;
 sockClient.Close();}

解决方案 »

  1.   

    笑什么啊??怎么没人也贴点基本操作的贴??万一以后忘了.可以来这直接用.
    比如用Event 大致的实现.
      

  2.   

    笑什么啊??怎么没人也贴点基本操作的贴??万一以后忘了.可以来这直接用.
    比如用Event 大致的实现
    >>楼主想得周到
      

  3.   

    DWORD WINAPI ThreadFunc(LPVOID lpParam)
    {
    #define PORT 34000 /// Select any free port you wish AfxSocketInit(NULL);
     CSocket sockSrvr; 
    -----------------------------------------------------
    这样的用法前无古人,后无来人,只能恭祝楼主仙福永享,代码寿与天齐楼下的保持队型