Yao Chunli
2022-06-21 e00d5a1575d26f8fec1be6fa8a844203cd66a24c
提交 | 用户 | age
4b03ae 1 // MyAsyncSocket1.cpp : 实现文件
Q 2 //
3
4 #include "stdafx.h"
5 #include "SocketFunc.h"
6 //#include "TCP_Server.h"
7 double GetTimeMs()
8 {
9     LARGE_INTEGER perfreq;
10     LARGE_INTEGER percounter1;    //,percounter2;
11     double time1;    //,time2,timeinter1;
12     QueryPerformanceFrequency(&perfreq);
13     QueryPerformanceCounter(&percounter1);
14 //    percounter1.QuadPart=rdtsc();
15 /*    _asm {
16             RDTSC;
17             mov percounter1.LowPart,eax;
18             mov    percounter1.HighPart,edx;
19     }
20 */    
21     time1=(double)percounter1.QuadPart/perfreq.QuadPart  ;
22 //    time2=(double)percounter2.QuadPart/perfreq.QuadPart  ;
23 //    timeinter1=time2-time1;
24     return (time1*1000);
25 };
26 // CMyServerSocket
27 CMyServerSocket::CMyServerSocket()
28 {
29     Idx=9999;
30     SN=0;
31 }
32 CMyServerSocket::~CMyServerSocket()
33 {
34
35 }
36 void CMyServerSocket::OnAccept(int nErrorCode)
37 {
38     CString s1;
39     int j;
40 //    s1.Format(_T("Server %d OnAccept Code %d\r\n"),Idx,nErrorCode);
41 //    SysLog(s1);
42     CMyDataSocket * MyAsyncSocket2;
43     int k=MySockets.size();
44     int bFound=0,pos=0;;
45     SN++;
46     MyAsyncSocket2=new CMyDataSocket;
47     MyAsyncSocket2->Idx=SN;
48     MyAsyncSocket2->ConnectionStat=MyAsyncSocket2->statConnected;
49     std::shared_ptr<CMyDataSocket> pMySocket(MyAsyncSocket2);
50     MySockets.push_back(pMySocket);
51
52     j=Accept(*MyAsyncSocket2);
53     MyAsyncSocket2->m_cTime=CTime::GetCurrentTime();
54     CString TimeStr=MyAsyncSocket2->m_cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
55
56     CString sip;
57     UINT nPort;
58     MyAsyncSocket2->GetPeerName(sip,nPort);
59     MyAsyncSocket2->sTargetIp=sip;
60     MyAsyncSocket2->nTargetPort=nPort;
61     MyAsyncSocket2->TargetVer.nMainVer=0;
62     MyAsyncSocket2->TargetVer.nSubVer=0;
63     MyAsyncSocket2->Logined=0;
64
65     s1.Format(_T("%d Code %d Accept = %d IP %s : %u  %s\r\n"),Idx,nErrorCode,j,sip,nPort,TimeStr);
66     SysLog(s1);
67     CAsyncSocket::OnAccept(nErrorCode);
68 }
69
70 void CMyServerSocket::OnClose(int nErrorCode)
71 {
72     CString s1;
73     s1.Format(_T("Server %d OnClose Code %d \r\n"),Idx,nErrorCode);
74     SysLog(s1);
75 }
76
77 void CMyServerSocket::OnConnect(int nErrorCode)
78 {
79     CString s1;
80     s1.Format(_T("Server %d OnConnect Code %d \r\n"),Idx,nErrorCode);
81     SysLog(s1);
82 }
83
84 int CMyServerSocket::UpdataStat()
85 {
86     CTime time1=CTime::GetCurrentTime();
87     int k=MySockets.size();
88     for (int i=k-1;i>=0;i--)
89     {
90         std::shared_ptr<CMyDataSocket> thissocket= MySockets.at(i);
91         if (thissocket->ConnectionStat == thissocket->statClosed)
92         {
93             CTimeSpan time2;
94             time2=time1-thissocket->m_kTime;
95             if (time2>10)
96             {
97                 MySockets.erase(MySockets.begin()+i);
98             }
99         }
100     }
101     return true;
102 }
103 // CMyAsyncSocket1
104 CMyDataSocket::CMyDataSocket()
105 {
106     SocketType=0;
107     Idx=0;    SN=0;    ConnectionStat=statIdel;
108     nPingInterval=0;nIntervalCount=0;
109     bPinging=0;    PingSeq=0;    latancy=0;
110
111     TotalSendBytes=TotalRecvBytes=0;
112     SendBytes=LastSendBytes=0;
113     RecvBytes=LastRecvBytes=0;
114     SendBuf.Alloc(SendBufSize);
115     RecvBuf.Alloc(RecvBufSize);
116     bToSendFile=0;    bSendingFile=0;    bRecvingFile=0;
117     DummyToSend=0;
118
119 }
120
121 CMyDataSocket::~CMyDataSocket()
122 {
123     Close();
124 }
125
126 // CMyAsyncSocket1 成员函数
127 stVerInfo MyVerInfo=
128 {
129     1,
130     1,
131 };
132 void CMyDataSocket::OnAccept(int nErrorCode)
133 {
134     // TODO: 在此添加专用代码和/或调用基类
135     CString s1;
136     s1.Format(_T("%d OnAccept Code %d\r\n"),Idx,nErrorCode);
137     SysLog(s1);
138     CAsyncSocket::OnAccept(nErrorCode);
139 }
140
141 void CMyDataSocket::OnClose(int nErrorCode)
142 {
143     // TODO: 在此添加专用代码和/或调用基类
144     CString s1;
145     s1.Format(_T("%d OnClose Code %d\r\n"),Idx,nErrorCode);
146     SysLog(s1);
147     ConnectionStat=statBeToClose;
148     CAsyncSocket::OnClose(nErrorCode);
149     ConnectionStat=statClosed;
150     m_kTime=CTime::GetCurrentTime();
151 /*
152     std::shared_ptr <CMyDataSocket1> p1;
153     int k=MySockets.size();
154     for (int i=0;i<k;i++)
155     {
156         if (MySockets.at(i)->Idx==Idx)
157         {
158     //        s1.Format(_T("%d ToDelete Self\r\n"),Idx);
159     //        SysLog(s1);
160             p1=MySockets.at(i);
161             MySockets.erase(MySockets.begin()+i);
162             break;
163         }
164     }
165 */
166 }
167
168 int CMyDataSocket::UpdateSpeed(void)
169 {
170
171     if ( nPingInterval>0)
172     {
173         nIntervalCount++;
174         if ( nIntervalCount >= nPingInterval ) 
175         {
176             nIntervalCount=0;
177             if ( bPinging ) {latancy=999.9; bPinging=0; }
178             DoPing();
179         }
180     }
181     SendSpeed=LastSendBytes+SendBytes;
182     RecvSpeed=LastRecvBytes+RecvBytes;
183     LastSendBytes=SendBytes;
184     LastRecvBytes=RecvBytes;
185     SendBytes=0;
186     RecvBytes=0;
187     return 0;
188 }
189
190 void CMyDataSocket::OnConnect(int nErrorCode)
191 {
192     // TODO: 在此添加专用代码和/或调用基类
193     SocketType=1;
194     ConnectionStat=statConnected;
195     CString s1;
196     s1.Format(_T("%d OnConnect Code %d\r\n"),Idx,nErrorCode);
197     SysLog(s1);
198     CAsyncSocket::OnConnect(nErrorCode);
199     char sendbuf2[2048];
200     pPacket p2=(pPacket)sendbuf2;
201     int len1=0;
202     len1=MakeDataPacket(p2,cmdVerInfo,1,dataTypeVerInfo,sizeof(MyVerInfo),&MyVerInfo);
203     SendPacket(p2,len1);
204
205     len1=MakeCtrlPacket(p2,cmdGetVersion,1);
206     SendPacket(p2,len1);
207
208     len1=MakeCtrlPacket(p2,cmdLogin,1);
209     SendPacket(p2,len1);
210
211 }
212
213 void CMyDataSocket::OnOutOfBandData(int nErrorCode)
214 {
215     // TODO: 在此添加专用代码和/或调用基类
216     CString s1;
217     s1.Format(_T("%d OnOutOfBandData Code %d\r\n"),Idx,nErrorCode);
218     SysLog(s1);
219     CAsyncSocket::OnOutOfBandData(nErrorCode);
220 }
221
222 void CMyDataSocket::OnReceive(int nErrorCode)
223 {
224     // TODO: 在此添加专用代码和/或调用基类
225
226     CString s1;
227     CString s3;
228     CStringA s4;
229     int i=0,j,k;
230     k=0;
231     int MaxRecvLength=65536;
232     CString sRipaddr;
233     UINT rport;
234     do{
235         int roomleft=0;
236         void * precvbuf=RecvBuf.GetWriteBuffer(&roomleft);
237         int thisRecvLength=min(MaxRecvLength,roomleft);
238         j=this->ReceiveFrom(precvbuf,thisRecvLength,sRipaddr,rport);
239         if (j!=SOCKET_ERROR) 
240         {RecvBuf.ReleaseWriteBuffer(j);RecvBytes+=j;TotalRecvBytes+=j;}
241         else {RecvBuf.ReleaseWriteBuffer(0);}
242
243         if (j!=SOCKET_ERROR)
244         {
245             do{
246                 int RecvBufDataSize=RecvBuf.GetDataSize();
247                 if (RecvBufDataSize<sizeof(tagPacket)){break;}    //剩余数据小于一个包头大小,退出
248                 pPacket p1;
249                 RecvBuf.CopyData(tempRecvbuf1,sizeof(tagPacket));
250                 p1=(pPacket)tempRecvbuf1;
251                 if (p1->sign==0x55aa)    //找到标记
252                 {
253                     int nDataSize=p1->nDataSize;
254                     int nPacketSize=sizeof(tagPacket)+nDataSize;        //获取包尺寸
255                     if (RecvBufDataSize<nPacketSize) break;            //剩余数据小于当前包大小,退出
256                     int nTailDataSize=RecvBuf.GetTailDataSize();
257                     if (nTailDataSize<nPacketSize)
258                     {
259                         RecvBuf.DelData(sizeof(tagPacket));
260                         RecvBuf.PopOut(tempRecvbuf1+sizeof(tagPacket),nDataSize);
261                         ProcessPacket(p1);
262                     }else
263                     {
264                         RecvBuf.DelData(sizeof(tagPacket));
265                         RecvBuf.PopOut(tempRecvbuf1+sizeof(tagPacket),nDataSize);
266                         ProcessPacket(p1);
267                     }
268
269                     //取得了一个完整的数据包,
270                     //s1.Format(_T("%d RecvPacket chn %d cmd %d Size %d DataSize %d\r\n"),Idx,p1->nChannel,p1->nCMD,nPacketSize,nDataSize);
271                     //SysLog(s1);
272                 }else
273                 {
274                     //RecvBuf.DelData(1);
275                     s1.Format(_T("%d 数据帧格式错误 \r\n"),Idx);
276                     for (int i=0;i<sizeof(tagPacket);i++)
277                     {
278                         s1.AppendFormat(_T("%02X "),(unsigned char)tempRecvbuf1[i]);
279                     }
280                     for (int i=0;i<sizeof(tagPacket);i++)
281                     {
282                         if (tempRecvbuf1[i]>=32&&tempRecvbuf1[i]<128)
283                         s1.AppendFormat(_T("%C"),(unsigned char)tempRecvbuf1[i]);
284                         else s1.Append(_T("."));
285                     }
286                     s1.AppendFormat(_T("\r\n"));
287                     SysLog(s1);
288                     RecvBuf.DelData(RecvBufDataSize);
289                 }
290                 i++;
291             }while (i<10);
292         }else
293         {
294             //CAsyncSocket::OnReceive(nErrorCode);
295             k=GetLastError();
296             //FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,k,0,s2.GetBuffer(2048),2048,NULL);
297             //s2.ReleaseBuffer();
298             s1.Format(_T("%d OnReceive %d Code %d %s:%d result %d err %d\r\n"),Idx,i,nErrorCode,sRipaddr,rport,j,k);
299             SysLog(s1);
300             //break;
301         }
302     }while (0);
303 }
304
305 void CMyDataSocket::OnSend(int nErrorCode)
306 {
307     // TODO: 在此添加专用代码和/或调用基类
308 //    char buf1[60000];
309     int j,k;
310     int MaxSendLength=65536;
311     CString s1;
312 //    s1.Format(_T("%d OnSend Code %d CountToSent %d BtS %lld\r\n"),Idx,nErrorCode,CountToSent,BytesToSend);
313 //    SysLog(s1);
314     CStringA s1A;
315     if (nErrorCode!=0) {return;}
316     int BytesToSend=SendBuf.GetDataSize();
317     if (nErrorCode==0)
318     {
319         while (BytesToSend>0)
320         {
321     //        Sleep(1);
322             int sendlenth=min(MaxSendLength,BytesToSend);
323             int leftdatasize;
324             char * psendbuf=SendBuf.GetReadBuffer(&leftdatasize);
325             int thissendlength=min(sendlenth,leftdatasize);
326             j=this->Send(psendbuf,thissendlength,0);
327             if (j!=SOCKET_ERROR) 
328             {
329                 TotalSendBytes+=j;
330                 SendBytes+=j;
331                 BytesToSend-=j;
332                 SendBuf.ReleaseReadBuffer(j);
333                 int leftdata=SendBuf.GetDataSize();
334 //                s1.Format(_T("%d SendBuf %d Left %d toSend %d Total %lld\r\n"),Idx,j,leftdata,BytesToSend,TotalSendBytes);
335 //                SysLog(s1);
336             }
337             else 
338             {
339                 SendBuf.ReleaseReadBuffer(0);
340                 k=GetLastError();
341                 //CString s2;
342                 //FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,k,0,s2.GetBuffer(2048),2048,NULL);
343                 //s2.ReleaseBuffer();
344                 //s1.Format(_T("Send Error %d %d\r\n"),j,k);
345                 //SysLog(s1);
346                 if (k==WSAEWOULDBLOCK) break;
347                 break;
348             }
349         };
350         while (BytesToSend==0&&bSendingFile)
351         {
352             int leftroom=SendBuf.GetLeftRoomSize();
353             if (leftroom<=(sizeof(tagPacket)+nMaxFileBlockSize))
354             {
355                 s1.Format(_T("%d LeftRoom %d < tagPacket Skip\r\n"),Idx,leftroom);
356                 SysLog(s1);
357                 break;
358             }
359             int ReadSize=min(leftroom-sizeof(tagPacket),nMaxFileBlockSize);
360             j=ContinueReadFile(tempSendbuf1,ReadSize);
361 //            nFileSentSize+=j;
362             if (j>0)
363             {
364                 k=this->SendTo(tempSendbuf1,j,0);
365                 if (k!=SOCKET_ERROR)
366                 {
367                     TotalSendBytes+=k;
368                     SendBytes+=k;
369 //                    s1.Format(_T("%d Send %d %lld\r\n"),Idx,k,TotalSendBytes);
370 //                    SysLog(s1);
371                 }
372                 if (k==SOCKET_ERROR)
373                 {
374                     SendBuf.PushIn(tempSendbuf1,j);
375                     int datasize=SendBuf.GetDataSize();
376 //                    s1.Format(_T("%d Pushin %d data %d \r\n"),Idx,j,datasize);
377 //                    SysLog(s1);
378                     int l=GetLastError();
379                     if (l==WSAEWOULDBLOCK) 
380                     {
381                         break;
382                     }
383                     break;
384                 }
385             }
386             if (j<ReadSize)
387             {
388                 bSendingFile=0;
389                 m_filesend1.Close();
390                 s1.Format(_T("%d 文件发送完毕\r\n"),Idx);
391                 SysLog(s1);
392                 break;
393             }
394         }
395         if (DummyToSend>0)
396         {
397             if (BytesToSend==0)
398             {
399                 while (DummyToSend>0)
400                 {
401                     int leftsize=SendBuf.GetLeftRoomSize();
402                     if (leftsize<sizeof(tagPacket)+16) break;
403                     int thissize=(int)min(leftsize-sizeof(tagPacket),min(DummyToSend,nMaxDummyBlockSize));
404                     if (thissize<=0) break;
405                     pPacket p2=(pPacket)tempSendbuf1;
406                     int len2=MakeDataPacket(p2,cmdSendDummyData,0,dataFileData,thissize,NULL);
407                     k=this->SendTo(tempSendbuf1,len2,0);
408                     if (k!=SOCKET_ERROR)
409                     {
410                         TotalSendBytes+=k;
411                         SendBytes+=k;
412                         DummyToSend-=thissize;
413                     }
414                     if (k==SOCKET_ERROR)
415                     {
416                         SendBuf.PushIn(tempSendbuf1,len2);
417                         DummyToSend-=thissize;
418                         int l=GetLastError();
419                         if (l==WSAEWOULDBLOCK)         {    break;    }
420                         break;
421                     }
422
423                 }
424             }else
425             {
426                 while (DummyToSend>0)
427                 {
428                     int leftsize=SendBuf.GetLeftRoomSize();
429                     if (leftsize<sizeof(tagPacket)+16) break;
430                     int thissize=(int)min(leftsize-sizeof(tagPacket),min(DummyToSend,nMaxDummyBlockSize));
431                     if (thissize<=0) break;
432                     pPacket p2=(pPacket)tempSendbuf1;
433                     int len2=MakeDataPacket(p2,cmdSendDummyData,0,dataFileData,thissize,NULL);
434                     SendBuf.PushIn(tempSendbuf1,len2);
435                     DummyToSend-=thissize;
436                 }
437             }
438         }
439     }
440     CAsyncSocket::OnSend(nErrorCode);
441 }
442
443 int CMyDataSocket::TriggerSend()
444 {
445     return AsyncSelect();
446 }
447 int CMyDataSocket::DoPing()
448 {
449     if (ConnectionStat==statConnected)
450     {
451         PingSeq++;
452         bPinging=1;
453         pingTime=GetTimeMs();
454         char sendbuf2[2048];
455         pPacket p2=(pPacket)sendbuf2;
456         int len1=MakeCtrlPacket(p2,cmdPing,PingSeq);
457         SendPacket(p2,len1);
458     }
459     return 0;
460 }
461 int CMyDataSocket::SendPacket(pPacket p2, int length)
462 {
463     SendBuf.PushIn(p2,length);
464     TriggerSend();
465     return length;
466 }
467
468 int CMyDataSocket::MakeCtrlPacket(pPacket p2,int Type, int nParam1)
469 {
470     p2->sign=0x55AA;
471     p2->nChannel=0;
472     p2->nCMD=Type;
473     p2->nDataType=dataNone;
474     p2->nDataSize=0;
475     p2->Param1=nParam1;
476
477     return sizeof(tagPacket)+p2->nDataSize;
478 }
479 int CMyDataSocket::MakeDataPacket(pPacket p2,int Type, int nParam1, int DataType, int nDataLen, void * DataBuf)
480 {
481     p2->sign=0x55AA;
482     p2->nChannel=0;
483     p2->nCMD=Type;
484     p2->nDataType=DataType;
485     p2->nDataSize=nDataLen;
486     p2->Param1=nParam1;
487     if (DataBuf!=NULL) memcpy_s(p2->data,1024,DataBuf,nDataLen);
488
489     return sizeof(tagPacket)+p2->nDataSize;
490 }
491
492 int CMyDataSocket::ProcessPacket(pPacket p1)
493 {
494     CString s1;
495     char tempsendbuf2[2048];
496     char databuf2[2048];
497     pPacket p2=(pPacket)tempsendbuf2;
498     int len=0;
499     double time1=GetTimeMs();
500     switch(p1->nCMD)
501     {
502         case cmdNone:
503             break;
504         case cmdPing:
505             len=MakeCtrlPacket(p2,cmdPingReply,p1->Param1);
506             SendPacket(p2,len);
507             break;
508         case cmdPingReply:
509             if (p1->Param1==PingSeq){    latancy=time1-pingTime;    bPinging=0;}
510             break;
511         case cmdHeartBeat:
512             break;
513         case cmdMessage:
514             break;
515         case cmdGetVersion:
516             len=MakeDataPacket(p2,cmdVerInfo,1,dataTypeVerInfo,sizeof(stVerInfo),&MyVerInfo);
517             SendPacket(p2,len);
518             break;
519         case cmdVerInfo:
520             TargetVer=*(stVerInfo *)(p1->data);
521             break;
522         case cmdLogin:
523             if (p1->Param1==1)
524             {
525                 len=MakeDataPacket(p2,cmdAcceptLogin,1,1,10,databuf2);
526                 SendPacket(p2,len);
527                 //Logined=1;
528             }
529             break;
530         case cmdLogout:
531             break;
532         case cmdAcceptLogin:
533             Logined=1;
534             break;
535         case cmdSendDummyData:
536             len=MakeCtrlPacket(p2,cmdNone,1);
537             SendPacket(p2,len);
538             break;
539         case cmdSendFile:
540             if (p1->nDataType==dataFileInfo)
541             {
542                 pFileInfo pf1=(pFileInfo)p1->data;
543                 DoRecvFile(pf1);
544             }
545             break;
546         case cmdAcceptFile:
547             if (bToSendFile)    //准备发送文件
548             {
549                 if (p1->Param1==0)    //对方拒绝
550                 {
551                     s1.Format(_T("%d 对方拒绝文件\r\n"),Idx);
552                     SysLog(s1);
553                     bToSendFile=0;
554                     m_filesend1.Close();    //文件关闭;
555                 }else if (p1->Param1==1)
556                 {
557                     s1.Format(_T("%d 对方接受文件\r\n"),Idx);
558                     SysLog(s1);
559                     bToSendFile=0;
560                     bSendingFile=1;
561                     nSendFileSize=m_filesend1.GetLength();
562                     nFileSentSize=0;
563                     TriggerSend();
564                 }
565             }
566             break;
567         case cmdSendFileData:
568             if (bRecvingFile)
569             {
570                 if (p1->nDataType==dataFileData)
571                 m_filerecv1.Write(p1->data,p1->nDataSize);
572                 nFileRecvedSize+=p1->nDataSize;
573                 if (nFileRecvedSize>=nRecvFileSize)
574                 {
575                     CFileStatus status1;
576                     CString sFilePathName;
577                     sFilePathName=m_filerecv1.GetFilePath();
578                     status1.m_atime=mRecvFileInfo.m_aTime;
579                     status1.m_ctime=mRecvFileInfo.m_cTime;
580                     status1.m_mtime=mRecvFileInfo.m_mTime;
581                     status1.m_attribute=mRecvFileInfo.nFileAttr;
582                     status1.m_size=0;
583                     status1.m_szFullName[0]=0;
584                     m_filerecv1.Close();
585                     CFile::SetStatus(sFilePathName,status1);
586                     bRecvingFile=0;
587                     s1.Format(_T("%d 文件接收完毕\r\n"),Idx);
588                     SysLog(s1);
589                 }
590             }
591             break;
592         default:
593             break;
594     }
595     return 0;
596 }
597
598 int CMyDataSocket::SendFile(CString sFilePathName)
599 {
600     CString s1;
601     if (ConnectionStat!=statConnected) {return -1;}
602     if (bToSendFile) {return -1;}
603     if (bSendingFile) {return -1;}
604     char tempSendbuf2[2048];
605     CString sFileName;
606     CStringA sFileNameA;
607     pPacket pPacket1;
608     pFileInfo pFileInfo1;
609     pPacket1=(pPacket)tempSendbuf2;
610     pFileInfo1=(pFileInfo)pPacket1->data;
611
612     int j=m_filesend1.Open(sFilePathName,CFile::OpenFlags::modeRead|CFile::OpenFlags::shareDenyNone,&e1);
613     if (j)
614     {
615         sFileName=m_filesend1.GetFileName();
616         SHTCharToAnsi(sFileName,sFileNameA.GetBuffer(2048),2048);
617         sFileNameA.ReleaseBuffer();
618         int len1=(sFileNameA.GetLength()+1+3)&(-4);
619
620         CFileStatus status1;
621         m_filesend1.GetStatus(status1);
622         s1.Format(_T("Size of status1 %d \r\n"),sizeof(status1));
623         s1.AppendFormat(_T("Size of CTime %d \r\n"),sizeof(CTime));
624         s1.AppendFormat(_T("FileSize %lld \r\n"),status1.m_size);
625         s1.AppendFormat(_T("FileName %s \r\n"),status1.m_szFullName);
626         SysLog(s1);
627         pFileInfo1->m_aTime=status1.m_atime;
628         pFileInfo1->m_cTime=status1.m_ctime;
629         pFileInfo1->m_mTime=status1.m_mtime;
630         pFileInfo1->nFileSize=status1.m_size;
631         pFileInfo1->nFileAttr=status1.m_attribute;
632         pFileInfo1->nFileNameLength=len1;
633         strcpy_s(pFileInfo1->m_FileName,len1,sFileNameA);
634         pPacket1->sign=0x55aa;
635         pPacket1->nChannel=0;
636         pPacket1->nCMD=cmdSendFile;
637         pPacket1->Param1=0;
638         pPacket1->nDataType=dataFileInfo;
639         pPacket1->nDataSize=sizeof(tagFileInfo)+len1;
640         int SendLength=sizeof(tagPacket)+pPacket1->nDataSize;
641         s1.Format(_T("Len1 %d DataSize %d PacketSize %d \r\n"),len1,pPacket1->nDataSize,SendLength);
642         SysLog(s1);
643         SendBuf.PushIn(pPacket1,SendLength);
644         TriggerSend();
645         bToSendFile=1;
646 /*
647         int k=Send(pPacket1,SendLength);
648         if (k==SOCKET_ERROR)
649         {
650             k=GetLastError();
651             CString s2;
652             FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,k,0,s2.GetBuffer(2048),2048,NULL);
653             s2.ReleaseBuffer();
654             s1.Format(_T("Send Error %d %d %s\r\n"),j,k,s2);
655             SysLog(s1);
656             return -1;
657         }else
658         {
659             if (k<SendLength)
660             {
661                 s1.Format(_T("Send Error,ToSend %d Send %d"),SendLength,k);
662                 SysLog(s1);
663                 return -1;
664             }else
665             {
666                 bToSendFile=1;
667             }
668         }
669 */
670         return 0;
671     }else
672     {
673         CString sError;
674         e1.GetErrorMessage(sError.GetBuffer(2048),2048);
675         sError.ReleaseBuffer();
676         s1.Format(_T("打开文件 %s 失败 %s\r\n"),sFilePathName,sError);
677         SysLog(s1);
678         return -1;
679     }
680     return 0;
681 }
682
683 int CMyDataSocket::ContinueReadFile(char * pFileBuf, int nBlockSize)
684 {
685     CString s1;
686     INT64 FileLeftSize;
687     FileLeftSize=nSendFileSize-nFileSentSize;
688     if (FileLeftSize==0) return 0;
689     int ReadDataLength=(int)min(nBlockSize,FileLeftSize);
690     int SendLength=ReadDataLength+sizeof(tagPacket);
691     pPacket p1;
692     p1=(pPacket)pFileBuf;
693     p1->sign=0x55aa;
694     p1->nChannel=0;
695     p1->nCMD=cmdSendFileData;
696     p1->Param1=0;
697     p1->nDataType=dataFileData;
698     p1->nDataSize=ReadDataLength;
699     m_filesend1.Read(p1->data,ReadDataLength);
700     nFileSentSize+=ReadDataLength;
701 //    s1.Format(_T("%d ReadFile %d Total %lld\r\n"),Idx,ReadDataLength,nFileSentSize);
702 //    SysLog(s1);
703     return SendLength;
704 }
705
706 int CMyDataSocket::DoRecvFile(pFileInfo pf1)
707 {
708     CString s1;
709     CString sFileName;
710     CStringA sFileNameA;
711     CString sFilePathName;
712     sFileNameA=pf1->m_FileName;
713     INT64 nFileLength=pf1->nFileSize;
714     SHAnsiToTChar(sFileNameA,sFileName.GetBuffer(2048),2048);
715     sFileName.ReleaseBuffer();
716     s1.Format(_T("%d 对方发来文件 %s Size %lld \r\n"),Idx,sFileName,nFileLength);
717     SysLog(s1);
718
719
720     int bAccept=0;    //拒绝/接受 0/1
721     if (bRecvingFile)
722     {
723         bAccept=0;        //拒绝
724     }else
725     {
726         CFileDialog dialog1(false,_T("*.*"),sFileName,OFN_OVERWRITEPROMPT,_T("*.*|*.*||"),NULL);
727         INT_PTR r=dialog1.DoModal();
728         if (r==IDOK)
729         {
730             CFileException e1;
731             sFilePathName=dialog1.GetPathName();
732             int j=m_filerecv1.Open(sFilePathName,CFile::modeCreate|CFile::modeWrite,&e1);
733             if (j)
734             {
735                 bAccept=1;        //接受
736                 bRecvingFile=1;
737                 mRecvFileInfo.m_aTime=pf1->m_aTime;
738                 mRecvFileInfo.m_cTime=pf1->m_cTime;
739                 mRecvFileInfo.m_mTime=pf1->m_mTime;
740                 mRecvFileInfo.nFileAttr=pf1->nFileAttr;
741                 mRecvFileInfo.nFileSize=pf1->nFileSize;
742                 nRecvFileSize=pf1->nFileSize;
743                 nFileRecvedSize=0;
744                 s1.Format(_T("%d 接受 另存为 %s \r\n"),Idx,sFilePathName);
745             }else
746             {
747                 bAccept=0;
748                 s1.Format(_T("%d 拒绝\r\n"),Idx);
749             }
750
751         }else
752         {
753             bAccept=0;        //拒绝
754             s1.Format(_T("%d 接收中,拒绝\r\n"),Idx);
755         }
756     }
757     SysLog(s1);
758     char tempsendbuf2[2048];
759     pPacket p2;
760     p2=(pPacket)tempsendbuf2;
761     int len1=MakeCtrlPacket(p2,cmdAcceptFile,bAccept);
762     SendPacket(p2,len1);
763     return 0;
764 }
765
766 int CMyDataSocket::StartSendMass(int Length, int Count)
767 {
768     DummyToSend+=Length*Count;
769     TriggerSend();
770     return 0;
771 }
772
773 CMyPingSocket::CMyPingSocket()
774 {
775     TotalHosts=0;
776     seq=0;
777 }
778 CMyPingSocket::~CMyPingSocket()
779 {
780
781 }
782 int CMyPingSocket::Init()
783 {
784     CString s1;
785     int i=0;
786     if (m_hSocket==INVALID_SOCKET)
787     {
788         i=Socket(SOCK_RAW,63,IPPROTO_ICMP,PF_INET);
789         s1.Format(_T("Create Ping Sock_raw = %d \r\n"),i);
790         SysLog(s1);
791     }
792     return i;
793 }
794 USHORT CMyPingSocket::checksum(USHORT * pBuf,int iSize)
795 {
796     unsigned long cksum=0;
797     while(iSize>1)
798     {
799         cksum+=*pBuf++;
800         iSize-=sizeof(USHORT);
801     }
802     if(iSize)
803         cksum+=*(UCHAR*)pBuf;
804     cksum=(cksum>>16)+(cksum&0xffff);
805     cksum+=(cksum>>16);
806     return (USHORT)(~cksum);
807 }
808 void CMyPingSocket::fill_icmp_data(char * pBuf,int iSize)
809 {
810     char a='a';
811     for (int i=0;i<iSize;i++)
812     {
813         pBuf[i]=a;
814         a++;
815         if (a>='v') {a='a';}
816     }
817 }
818 void CMyPingSocket::OnReceive(int nErrorCode)
819 {
820     CString s1;
821     int RecvLength=65536;
822     CString sRipaddr;
823     UINT rport;
824     int j=0;
825     if (nErrorCode==0)
826     {
827         j=ReceiveFrom(RecvBuf1,RecvLength,sRipaddr,rport);
828 //        s1.Format(_T("Recv From %s %d Bytes \r\n"),sRipaddr,j);
829 //        SysLog(s1);
830         if (j<sizeof(IpHeader)+sizeof(IcmpHeader)) return;
831         IpHeader * pIp=(IpHeader *)RecvBuf1;
832         IcmpHeader * picmp1=(IcmpHeader *)(&RecvBuf1[0]+sizeof(IpHeader));
833         if (pIp->protocol==IPPROTO_ICMP)
834         {
835             int thisseq=ntohs(picmp1->i_seq);
836                 
837             double thistime=GetTimeMs();
838             for (int i=0;i<TotalHosts;i++)
839             {
840                 if (thisseq==Hosts[i].seq)
841                 {
842                     Hosts[i].Replied=true;
843                     s1.Format(_T("Reply From %s(%s) %d Bytes time %.3fmS TTL %d\r\n"),Hosts[i].sHostName,sRipaddr,j-sizeof(IpHeader)-sizeof(IcmpHeader),thistime-Hosts[i].PingTime,pIp->tt1);
844                     SysLog(s1);
845                     break;
846                 }
847             }
848
849         }
850     }
851 }
852 int CMyPingSocket::DoPings()
853 {
854     //先准备数据
855     CString s1;
856     int datasize=32;
857     IcmpHeader * picmp1=(IcmpHeader *)SendBuf1;
858     picmp1->i_type=8;
859     picmp1->i_code=0;
860     picmp1->i_id=htons(4);
861     fill_icmp_data(picmp1->datas,datasize);
862
863     picmp1->i_seq=htons(seq);
864     picmp1->i_cksum=0;
865     picmp1->i_cksum=checksum((USHORT *)picmp1,sizeof(IcmpHeader)+datasize);
866     
867     for (int i=0;i<TotalHosts;i++)
868     {
869         seq++;
870         picmp1->i_seq=htons(seq);    
871         picmp1->i_cksum=0;
872         picmp1->i_cksum=checksum((USHORT *)picmp1,sizeof(IcmpHeader)+datasize);
873         Hosts[i].seq=seq;
874         if (Hosts[i].Pinging&&!Hosts[i].Replied)
875         {
876             s1.Format(_T("Request %s TimeOut\r\n"),Hosts[i].sHostName);
877             SysLog(s1);
878         }
879         Hosts[i].Pinging=true;
880         Hosts[i].Replied=false;
881         int j=SendTo(SendBuf1,sizeof(IcmpHeader)+datasize,0,Hosts[i].sHostName,0);
882         Hosts[i].PingTime=GetTimeMs();
883         s1.Format(_T("Ping %s = %d \r\n"),Hosts[i].sHostName,j);
884 //        SysLog(s1);
885     }
886     return 0;
887 }
888 int CMyPingSocket::AddHostToList(CString HostAddr)
889 {
890     if (m_hSocket==INVALID_SOCKET) Init();
891     if ( TotalHosts+1 >= 100 ) {return -1;}
892     Hosts[TotalHosts].sHostName = HostAddr;
893     Hosts[TotalHosts].Pinging = false;
894     Hosts[TotalHosts].Replied = false;
895     TotalHosts++;
896     return 0;
897 }
898 int CMyPingSocket::DelHostFromList(int index)
899 {
900     return index;
901 }
902 int CMyPingSocket::EmptyList()
903 {
904     TotalHosts=0;
905     return 0;
906 }
907
908 void CMyUDPSocket1::OnReceive(int nErrorCode)
909 {
910     CString s1;
911     int RecvLength=65536;
912     CString sRipaddr;
913     UINT rport;
914     int j=0;
915     char * recvbuf[65536];
916     if (nErrorCode==0)
917     {
918         j=ReceiveFrom(recvbuf,RecvLength,sRipaddr,rport);
919         //        s1.Format(_T("Recv From %s %d Bytes \r\n"),sRipaddr,j);
920         //        SysLog(s1);
921         s1.Format(_T("1Recv From %s(%d) %d Bytes\r\n"),sRipaddr,rport,j);
922         SysLog(s1);
923
924     }
925 }
926
927 void CMyUDPSocket2::OnReceive(int nErrorCode)
928 {
929     CString s1;
930     int RecvLength=65536;
931     CString sRipaddr;
932     UINT rport;
933     int j=0;
934     char * recvbuf[65536];
935     if (nErrorCode==0)
936     {
937         j=ReceiveFrom(recvbuf,RecvLength,sRipaddr,rport);
938         //        s1.Format(_T("Recv From %s %d Bytes \r\n"),sRipaddr,j);
939         //        SysLog(s1);
940         s1.Format(_T("2Recv From %s(%d) %d Bytes\r\n"),sRipaddr,rport,j);
941         SysLog(s1);
942
943     }
944 }
945
946 void CMyUDPSocket3::OnReceive(int nErrorCode)
947 {
948     CString s1;
949     int RecvLength=65536;
950     CString sRipaddr;
951     UINT rport;
952     int j=0;
953     char * recvbuf[65536];
954     if (nErrorCode==0)
955     {
956         j=ReceiveFrom(recvbuf,RecvLength,sRipaddr,rport);
957         //        s1.Format(_T("Recv From %s %d Bytes \r\n"),sRipaddr,j);
958         //        SysLog(s1);
959         s1.Format(_T("3Recv From %s(%d) %d Bytes\r\n"),sRipaddr,rport,j);
960         SysLog(s1);
961
962     }
963 }