Socket点对点聊天+文件传输





 Socket编程。 


socket:
设计一个点对点聊天小程序。

  1. 使用原生socket api实现,即不使用MFC中的socket类,也不使用其他高级socket框架
  2. 需要先设计一套协议
  3. 有GUI界面
  4. 可互相传递文字和文件
  5. 即时反应对方的在线还是离线

初级版

1.在应用程序类重载的InitInstance函数中调用AfxSocketInit()函数,加载套接字。

1
2
3
4
5
if(!AfxSocketInit())
{
AfxMessageBox("加载套接字库失败!");
return FALSE;
}

2.在你的对话框类中添加如下函数InitSocket(),初始化套接字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
BOOL CChatDlg::InitSocket()
{
m_socket=socket(AF_INET,SOCK_DGRAM,0);
if(INVALID_SOCKET==m_socket)
{
MessageBox("套接字创建失败!");
return FALSE;
}
SOCKADDR_IN addrSock;
addrSock.sin_family=AF_INET;
addrSock.sin_port=htons(5000);
addrSock.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

int retval;
retval=bind(m_socket,(SOCKADDR*)&addrSock,sizeof(SOCKADDR));
if(SOCKET_ERROR==retval)
{
closesocket(m_socket);
MessageBox("绑定失败!");
return FALSE;
}
return TRUE;

}

3.在对话框类的OnInitDialog()函数中调用上述InitSocket()函数,初始化套接字,同时创建一个线程接收数据:

1
2
3
4
5
RECVPARAM *pRecvParam=new RECVPARAM;
pRecvParam->sock=m_socket;
pRecvParam->hwnd=m_hWnd;
HANDLE hThread=CreateThread(NULL,0,RecvProc,(LPVOID)pRecvParam,0,NULL);
CloseHandle(hThread);

其中

1
2
3
4
5
struct RECVPARAM
{
SOCKET sock;
HWND hwnd;
};

是自定义结构体

4.接收线程函数RecvProc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DWORD WINAPI CChatDlg::RecvProc(LPVOID lpParameter)
{
SOCKET sock=((RECVPARAM*)lpParameter)->sock;
HWND hwnd=((RECVPARAM*)lpParameter)->hwnd;
delete lpParameter;
SOCKADDR_IN addrFrom;
int len=sizeof(SOCKADDR);
char recvBuf[200];
int retval;
while(TRUE)
{
retval=recvfrom(sock,recvBuf,200,0,(SOCKADDR*)&addrFrom,&len);
if(SOCKET_ERROR==retval)
break;
}
return 0;
}

recvBuf中就保存了你要的数据。
初级版

中级版

界面

原始界面

聊天:
TCP

传文件:
服务器
传文件

客户端
传文件2

显示文件传输进度:
传输过程

传输成功,可以正常打开文件。
传输成功

下线:
下线

关于:
关于

源程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075

// traDlg.cpp : implementation file
//

#include "stdafx.h"
#include "tra.h"
#include "traDlg.h"

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

#include <dlgs.h>
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
CAboutDlg();

// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA

// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL

// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CtraDlg dialog



#define PORT 34567
#define FLAG 2
#define SIZEFILE 1024

const int SOCK_TCP = 0; //TCP模式
const int SOCK_UDP = 1; //UDP模式

CWinThread *pThreadSendFile; //发送文件线程-->_SendFileThread
CWinThread *pThreadSendMsg; //发送消息线程
CWinThread *pThreadLisen; //监听线程-->_ListenTcpThread
CWinThread *pReceiveThread; //接受线程-->_ReceiveThread



//////////////////////////////////////////////////////////////////////////////


CtraDlg::CtraDlg(CWnd* pParent /*=NULL*/)
: CDialog(CtraDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CtraDlg)
m_MsgSend = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_nSockType = 0;//TCP
m_WorkType = 2;//两者
m_client = 0;
m_server = 0;
FileWork = false;
FileStop = false;
StopServer = false;
}

void CtraDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CtraDlg)
DDX_Control(pDX, IDC_PROGRESS_SEND_FILE, m_Progress);
DDX_Control(pDX, IDC_LIST_BOX_ADDMSG, m_AddMsgLIst);
DDX_Control(pDX, IDC_IPADDRESS, m_You_IP);
DDX_Text(pDX, IDC_EDIT_SENDMSG, m_MsgSend);
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CtraDlg, CDialog)
//{{AFX_MSG_MAP(CtraDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_CONNECT, OnButtonConnect)
ON_BN_CLICKED(IDC_BUTTON_DISCONNECT, OnButtonDisconnect)
ON_BN_CLICKED(IDC_BUTTON_SEND_MSG, OnButtonSendMsg)
ON_BN_CLICKED(IDC_BUTTON_SEND_FILE, OnButtonSendFile)
ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear)
ON_BN_CLICKED(IDC_RADIO_TCP, OnRadioTcp)
ON_BN_CLICKED(IDC_RADIO_UDP, OnRadioUdp)
ON_BN_CLICKED(IDC_RADIO_SERVER, OnRadioServer)
ON_BN_CLICKED(IDC_RADIO_CLIENT, OnRadioClient)
ON_BN_CLICKED(IDC_RADIO_BOTH, OnRadioBoth)
ON_BN_CLICKED(IDC_BUTTON_STOP_FILE, OnButtonStopFile)
ON_MESSAGE(WM_KSEND,OnKSend)
//ON_BN_CLICKED(IDC_BUTTON_CAPUTER, OnButtonCaputer)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CtraDlg message handlers

BOOL CtraDlg::OnInitDialog()
{
CDialog::OnInitDialog();

// Add "About..." menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}

// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon

// TODO: Add extra initialization here
/////////////////////////////////////////////////////////
CString strLocalName;
GetLocalHostName(strLocalName);
CString strLocalIP;
GetIpAddress(strLocalName,strLocalIP);
m_You_IP.SetWindowText("127.0.0.1"); //设置默认IP
/////////////////////////////////////////////////////////
((CButton*)GetDlgItem(IDC_RADIO_BOTH))->SetCheck(BST_CHECKED);//默认为服务器、客户端一体
SetWindowText("博靖牌聊天+文件传输小工具");

GetDlgItem(IDC_BUTTON_CONNECT)->SetWindowText("启动");
GetDlgItem(IDC_BUTTON_DISCONNECT)->SetWindowText("关闭");

//GetDlgItem(IDC_BUTTON_CAPUTER)->EnableWindow(false);//默认为不可用
((CButton*)GetDlgItem(IDC_RADIO_TCP))->SetCheck(BST_CHECKED);//默认为TCP
GetDlgItem(IDC_BUTTON_SEND_MSG)->EnableWindow(false);//发送消息不可用
GetDlgItem(IDC_BUTTON_SEND_FILE)->EnableWindow(false);//发送文件不可用
GetDlgItem(IDC_BUTTON_CLEAR)->EnableWindow(false);//清除不可用
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(false);//断开连接不可用
GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_HIDE);
return TRUE; // return TRUE unless you set the focus to a control
}

void CtraDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}

// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.

void CtraDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting

SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;

// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}

// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CtraDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}

/**************************************线程************************************************/

/******************************服务器线程开始***********************************************/
//TCP监听线程
UINT _ListenTcpThread(LPVOID lparam)
{
CtraDlg *pDlg=(CtraDlg *)lparam;
if (pDlg->StopServer==true)
{
return -1;
}
CSocket sockSrvr;
pDlg->m_Potr = PORT+pDlg->m_server;//保存当前使用端口,用于关闭
int createSucceed=sockSrvr.Create(pDlg->m_Potr);
if (createSucceed == 0)
{
AfxMessageBox("ListenTcpThread Create错误!"+pDlg->GetError(GetLastError()));
return -1;
}

int listenSucceed=sockSrvr.Listen(); //开始监听
if(listenSucceed==0)
{
AfxMessageBox("ListenTcpThread Listen错误!"+pDlg->GetError(GetLastError()));
return -1;
}

CSocket recSo;
SOCKADDR_IN client;
int iAddrSize=sizeof(client);

int acceptSucceed=sockSrvr.Accept(recSo,(SOCKADDR *)&client,&iAddrSize); //接受连接并取得对方IP
if (acceptSucceed==0)
{
AfxMessageBox("ListenTcpThread Accept错误!"+pDlg->GetError(GetLastError()));
return -1;
}
sockSrvr.Close();
char flag[FLAG] = {0};
if (recSo.Receive(flag,FLAG) != 2)
{
return -1;
}
pDlg->m_type=flag[0];
if (pDlg->m_type=='D')
{
return 0;
}
pThreadLisen=::AfxBeginThread(_ListenTcpThread,pDlg);
pDlg->ReceiveFileMsg(recSo,client);
return 0;
}
UINT _UDPThread(LPVOID lparam) //UDP接受信息线程开始
{

CtraDlg *pDlg=(CtraDlg *)lparam;
if (pDlg->StopServer == true)
{
return -1;
}

CSocket sockSrvrUdp;
sockSrvrUdp.Create(PORT+pDlg->m_client,SOCK_DGRAM);
char buff[100] = {0};
int ret=0;
CString ipStr;
CString msg;
UINT port;
for(;;)
{

ret=sockSrvrUdp.ReceiveFrom(buff,100,ipStr,port);//IP和port均为返回值

if (buff[0]=='D')
{
return 0;
}
if (ret==SOCKET_ERROR)
{
break;
}
msg.Format(buff);
pDlg->AddMsgList(ipStr,msg);
}
sockSrvrUdp.Close();
return 0;
}
//服务器线程结束
/*********************************************客户端线程开始*****************************************************/
//发送文件线程
UINT _SendFileThread(LPVOID lparam)
{

CtraDlg *pDlg = (CtraDlg *)lparam;
if (pDlg->StopServer == true)
{
return -1;
}
CSocket sockClient;
sockClient.Create();
CString ip;
pDlg->m_You_IP.GetWindowText(ip);
sockClient.Connect(ip, PORT+pDlg->m_client);
//首先发送标记F为文件,2
int end = 0;
end = sockClient.Send("F", FLAG);

//发送标志是否成功
if (end == SOCKET_ERROR)
{
AfxMessageBox("_SendFileThread Send错误!"+pDlg->GetError(GetLastError()));
return -1;
}

else if (end != 2)
{
AfxMessageBox("文件头错误!");
return -1;
}
///////////////////////////////////////////////////////////////////
CFile myFile;
FILEINFO myFileInfo;
if (!myFile.Open(pDlg->m_fileName, CFile::modeRead | CFile::typeBinary))
{
return -1;
}
myFileInfo.fileLength=myFile.GetLength(); //得到文件大小
strcpy(myFileInfo.fileName,myFile.GetFileName());//得到文件名称

sockClient.Send(&myFileInfo,sizeof(myFileInfo)); //发送文件信息

pDlg->m_Progress.SetRange32(0, myFileInfo.fileLength);

myFile.Seek(0, CFile::begin);
char m_buf[SIZEFILE] = {0};
CString strError;
int num = 0;
end = 0;
int temp = 0;
pDlg->GetDlgItem(IDC_BUTTON_STOP_FILE)->EnableWindow(true);

for (;;)
{
if (pDlg->FileWork == false)
{
pDlg->FileWork = true;
pDlg->GetDlgItem(IDCANCEL)->EnableWindow(false);
pDlg->GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(false);
}
num = myFile.Read(m_buf, SIZEFILE);
if (num == 0)
{
break;
}
end = sockClient.Send(m_buf, num);
temp += end;
pDlg->m_Progress.SetPos(temp);
if (pDlg->FileStop == true)
{
pDlg->FileStop = false;
pDlg->FileWork = false;
break;
}

if (end == SOCKET_ERROR)
{
AfxMessageBox("_SendFileThread Send错误!"+pDlg->GetError(GetLastError()));
break;

}
}
pDlg->m_Progress.SetPos(0);
CString strLocalName;
pDlg->GetLocalHostName(strLocalName);
CString strLocalIP;
pDlg->GetIpAddress(strLocalName,strLocalIP);
if(temp == myFileInfo.fileLength)
{
pDlg->AddMsgList(strLocalName, "文件发送成功!");
}
else
{
pDlg->AddMsgList(strLocalName, "文件发送失败!");
}
myFile.Close();
sockClient.Close();
pDlg->FileWork = false;
pDlg->GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_HIDE);
pDlg->GetDlgItem(IDC_BUTTON_STOP_FILE)->EnableWindow(false);

pDlg->GetDlgItem(IDCANCEL)->EnableWindow(true);
pDlg->GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(true);

return 0;
}



UINT _SendMsgThread(LPVOID lparam) //TCP发送信息线程
{

CtraDlg *pDlg=(CtraDlg *)lparam;
if (pDlg->StopServer == true)
{
return -1;
}
CSocket sockClient;
sockClient.Create();
CString ip,strError;
pDlg->m_You_IP.GetWindowText(ip);
int conn = sockClient.Connect(ip, PORT+pDlg->m_client);
if (conn == 0)
{
AfxMessageBox("_SendMsgThread Connect错误!"+pDlg->GetError(GetLastError()));
sockClient.ShutDown(2);
sockClient.Close();
AfxEndThread(1L);
return 0;

}
//首先发送标记M为信息,2
int end = 0;
end = sockClient.Send("M",FLAG);
if(end == SOCKET_ERROR)
{
AfxMessageBox("_SendMsgThread Send错误!"+pDlg->GetError(GetLastError()));
return -1;
}
else if(end != 2)
{
AfxMessageBox("消息头错误!");
return -1;
}
CString strMsg = pDlg->m_MsgSend;
end = sockClient.Send(strMsg,strMsg.GetLength());
if (end == SOCKET_ERROR)
{
AfxMessageBox("_SendMsgThread Send错误!"+pDlg->GetError(GetLastError()));
return -1;
}
CString strLocalName;
pDlg->GetLocalHostName(strLocalName);
CString strLocalIP;
pDlg->GetIpAddress(strLocalName,strLocalIP);
pDlg->AddMsgList(strLocalName,strMsg);
int i=0;
sockClient.Close();

return 0;
}

///////////////////////////////////////////////////////////////////
UINT _SendMsgUdpThread(LPVOID lparam) //UDP发送信息
{

CtraDlg *pDlg = (CtraDlg *)lparam;
if (pDlg->StopServer == true)
{
return -1;
}
CSocket sockClientUdp;
pDlg->m_type = PORT+pDlg->m_client+10;
sockClientUdp.Create(pDlg->m_type, SOCK_DGRAM);
CString strMsg = pDlg->m_MsgSend;
int ret = 0;
CString ipStr;
pDlg->m_You_IP.GetWindowText(ipStr);
UINT port = PORT+pDlg->m_server;
ret=sockClientUdp.SendTo(strMsg, strMsg.GetLength(), port, ipStr);
if (ret == SOCKET_ERROR)
{
DWORD error = GetLastError();

}
CString strLocalName;
pDlg->GetLocalHostName(strLocalName);
CString strLocalIP;
pDlg->GetIpAddress(strLocalName, strLocalIP);
pDlg->AddMsgList(strLocalName, strMsg);
sockClientUdp.Close();
return 0;

}

/************************************客户端线程结束**********************************/

/*************************************函数****************************************/

int CtraDlg::ReceiveFileMsg(CSocket &recSo,SOCKADDR_IN &client)//接受函数
{
if (m_type == 'F') //文件
{
SaveYouFile(recSo, client);
}

else if (m_type == 'M') //信息
{
char buff[100] = {0};
CString msg;
int ret = 0;
for (;;)
{
ret = recSo.Receive(buff,100);
if (ret == 0)
{
break;
}
msg += buff;
}
CString strOut,strIn;
m_You_IP.GetWindowText(strIn);
GetNamebyAddress(strIn,strOut);
CString youName;
// youName.Format(inet_ntoa(client.sin_addr));
// CString str = youName+"<-"+strOut;
CString str = strOut;
AddMsgList(str, msg);
}
recSo.Close();
return 0;
}


int CtraDlg::SaveYouFile(CSocket &recSo, SOCKADDR_IN &client)//接受文件
{
CString fname;
CFileDialog dlg(false); //另存文件
FILEINFO myFileInfo;
recSo.Receive(&myFileInfo, sizeof(FILEINFO));
int fileLength=myFileInfo.fileLength;
CString strfileIp,strfileName,strfileLength;
strfileIp.Format(inet_ntoa(client.sin_addr));
strfileName.Format(myFileInfo.fileName);
strfileLength.Format("%f", myFileInfo.fileLength/1024.0);
CString title = "文件"+strfileName + " 大小" + strfileLength + "KB " + "来自" + strfileIp + " 是否接受?";
dlg.m_ofn.lpstrTitle = title;//标题条
char fileme[500] = {0};//必须足够大小
strcpy(fileme, strfileName);
dlg.m_ofn.lpstrFile = fileme; //文件名称
if (dlg.DoModal() == IDOK)
{
fname = dlg.GetPathName(); //得到文件名名称、路径
GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_SHOW);
}
else
{
GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_BUTTON_STOP_FILE)->EnableWindow(false);

GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(true);
GetDlgItem(IDCANCEL)->EnableWindow(true);

recSo.Close();
return 0;

}
char buf[SIZEFILE] = {0};
CFile f(fname, CFile::modeCreate|CFile::modeWrite); //存文件

m_Progress.SetRange32(0,fileLength);

int n = 0; //接受的字节数 0表示结束
int temp = 0;
GetDlgItem(IDC_BUTTON_STOP_FILE)->EnableWindow(true);

GetDlgItem(IDCANCEL)->EnableWindow(false);
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(false);


for (;;)
{
n = recSo.Receive(buf,SIZEFILE); //接受
if (n == 0) //0表示结束
{
break;//接受完毕
}
f.Write(buf,n);
temp += n;
m_Progress.SetPos(temp);
if (FileWork == false)
{
FileWork = true;
}
if (FileStop == true)
{
FileStop = false;
FileWork = false;
break;
}

}
f.Close();
m_Progress.SetPos(0);
if (temp == fileLength)
{
AddMsgList(inet_ntoa(client.sin_addr),"文件接收成功!");
}
else
{
AddMsgList(inet_ntoa(client.sin_addr),"文件接收失败!");
}

FileWork = false;
GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_BUTTON_STOP_FILE)->EnableWindow(false);

GetDlgItem(IDCANCEL)->EnableWindow(true);
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(true);
return 0;
}

/*********************************************按钮*****************************************/


void CtraDlg::OnButtonConnect() //开始连接
{
// TODO: Add your control notification handler code here
CString str;
m_You_IP.GetWindowText(str);
CString strOut,strIn;
m_You_IP.GetWindowText(strIn);
if(GetNamebyAddress(strIn,strOut) == -1)
{
GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(true);//连接不可用
return;
}
//m_MsgSend = "你好" + strOut + "!";
m_MsgSend =" ";
UpdateData(false);

if (m_nSockType == SOCK_TCP)
{

pThreadLisen=::AfxBeginThread(_ListenTcpThread,this); //开始TCP线程
GetDlgItem(IDC_BUTTON_SEND_MSG)->EnableWindow(true);//发送消息可用
GetDlgItem(IDC_BUTTON_SEND_FILE)->EnableWindow(true);//文件可用

//显示上线
CString strLocalName;
GetLocalHostName(strLocalName);
AddMsgList(strLocalName, "上线!");
}
else
{
pThreadLisen=::AfxBeginThread(_UDPThread,this); //开始UDP线程
GetDlgItem(IDC_BUTTON_SEND_MSG)->EnableWindow(true);//发送可用
GetDlgItem(IDC_BUTTON_SEND_FILE)->EnableWindow(false);//文件不可用

//显示上线
CString strLocalName;
GetLocalHostName(strLocalName);
AddMsgList(strLocalName, "上线!");
}

GetDlgItem(IDC_RADIO_TCP)->EnableWindow(false);//单选不可用
GetDlgItem(IDC_RADIO_UDP)->EnableWindow(false);//单选不可用
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(true);//断开可用
GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(false);//连接不可用
GetDlgItem(IDC_RADIO_SERVER)->EnableWindow(false);
GetDlgItem(IDC_RADIO_CLIENT)->EnableWindow(false);
GetDlgItem(IDC_RADIO_BOTH)->EnableWindow(false);
GetDlgItem(IDC_IPADDRESS)->EnableWindow(false);



}

void CtraDlg::OnButtonDisconnect() //关闭
{
// TODO: Add your control notification handler code here
GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(true);
GetDlgItem(IDC_RADIO_TCP)->EnableWindow(true);
((CButton*)GetDlgItem(IDC_RADIO_UDP))->EnableWindow(true);
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(false);
GetDlgItem(IDC_BUTTON_SEND_MSG)->EnableWindow(false);
GetDlgItem(IDC_BUTTON_SEND_FILE)->EnableWindow(false);
m_AddMsgLIst.ResetContent();
GetDlgItem(IDC_BUTTON_CLEAR)->EnableWindow(false);
((CButton*)GetDlgItem(IDC_RADIO_SERVER))->EnableWindow(true);
((CButton*)GetDlgItem(IDC_RADIO_CLIENT))->EnableWindow(true);
((CButton*)GetDlgItem(IDC_RADIO_BOTH))->EnableWindow(true);
GetDlgItem(IDC_IPADDRESS)->EnableWindow(true);
m_AddMsgLIst.SendMessage(LB_SETHORIZONTALEXTENT,0,0);



/**********************************************发送结束***********************************************/
if(m_nSockType == SOCK_TCP)
{
DWORD dwStatus;
if (pThreadLisen != NULL)
{
if(::GetExitCodeThread(pThreadLisen->m_hThread, &dwStatus)==0)
{
int errror = GetLastError();
return;
}
if (dwStatus == STILL_ACTIVE)
{
CSocket sockClient;
sockClient.Create();
CString ip,strError;
ip="127.0.0.1";
int conn = sockClient.Connect(ip, m_Potr);
if (conn == 0)
{
AfxMessageBox("关闭错误!"+GetError(GetLastError()));
sockClient.ShutDown(2);
sockClient.Close();
return;

}
sockClient.Send("D",FLAG); //结束

}
else
{
delete pThreadLisen;
pThreadLisen = NULL;
}
}
}
else
{
CSocket sockClientUdp;
int succeedCreate = sockClientUdp.Create(m_type, SOCK_DGRAM);
CString strMsg = "D";
int ret = 0;
CString ipStr;
m_You_IP.GetWindowText(ipStr);
UINT port = PORT+m_server;
ret = sockClientUdp.SendTo(strMsg, 1, port, ipStr);

}
//显示下线
CString strLocalName;
GetLocalHostName(strLocalName);
AddMsgList(strLocalName, "下线!");
}

void CtraDlg::OnButtonSendMsg() //发送消息
{
// TODO: Add your control notification handler code here
UpdateData(true);
if (m_MsgSend.GetLength() == 0)
{
return;
}
if (m_nSockType == SOCK_TCP)
{
::AfxBeginThread(_SendMsgThread, this);
}
else
{
::AfxBeginThread(_SendMsgUdpThread, this);
}
SetDlgItemText(IDC_EDIT_SENDMSG, "");
}


void CtraDlg::OnButtonSendFile() //发送文件
{
// TODO: Add your control notification handler code here
CFileDialog dlg(true);
CString ip;
m_You_IP.GetWindowText(ip);
CString title = "文件发往" + ip + "请选择";
dlg.m_ofn.lpstrTitle = title;//标题条
if (dlg.DoModal() == IDOK)
{
m_fileName = dlg.GetPathName();
GetDlgItem(IDC_PROGRESS_SEND_FILE)->ShowWindow(SW_SHOW);
pThreadSendFile=::AfxBeginThread(_SendFileThread, this); //开始传送文件线程
}

}

void CtraDlg::AddMsgList(CString IP,CString str) //添加信息于LISTBOX 控件中
{
SYSTEMTIME tm;
GetLocalTime(&tm);
CString time;
time.Format(_T(" %d:%02.2d "), tm.wHour, tm.wMinute);
m_AddMsgLIst.AddString(IP+"("+time+")"+str);
int numList = m_AddMsgLIst.GetCount()-1;
GetDlgItem(IDC_BUTTON_CLEAR)->EnableWindow(true);
m_AddMsgLIst.SetTopIndex(numList);
m_AddMsgLIst.SetCurSel(numList);
//水平滚动
int max_width = 0;
CSize sz;
CClientDC dc(this);
for (int i = 0; i<m_AddMsgLIst.GetCount(); i++)
{
m_AddMsgLIst.GetText(i,str);
sz = dc.GetTextExtent(str);
if (max_width < sz.cx)
{
max_width = sz.cx;
}
}
m_AddMsgLIst.SendMessage(LB_SETHORIZONTALEXTENT,max_width,0);

}

void CtraDlg::OnButtonClear() //清除聊天内容
{
// TODO: Add your control notification handler code here
m_AddMsgLIst.ResetContent();
GetDlgItem(IDC_BUTTON_CLEAR)->EnableWindow(false);
m_AddMsgLIst.SendMessage(LB_SETHORIZONTALEXTENT,0,0);

}

void CtraDlg::OnRadioTcp() //选择TCP模式
{
// TODO: Add your control notification handler code here
m_nSockType = SOCK_TCP;
CString text;
if (m_WorkType== 0)
{
text = "服务器";
}
else if (m_WorkType == 1)
{
text = "客户端";
}
else
{
text = "小工具";
}
SetWindowText(text + "TCP方式");

}

void CtraDlg::OnRadioUdp() //选择UDP模式
{
// TODO: Add your control notification handler code here
m_nSockType = SOCK_UDP;
CString text;
if (m_WorkType == 0)
{
text = "服务器";
}
else if (m_WorkType == 1)
{
text = "客户端";
}
else
{
text = "小工具";
}
SetWindowText(text + "UDP方式");


}

CString CtraDlg::GetError(DWORD error) //返回错误信息
{
CString strError;
switch(error)
{
case WSANOTINITIALISED:
strError = "初始化错误";
break;
case WSAENOTCONN:
strError = "对方没有启动";
break;
case WSAEWOULDBLOCK :
strError = "对方已经关闭";
break;
case WSAECONNREFUSED:
strError = "连接的尝试被拒绝";
break;
case WSAENOTSOCK:
strError = "在一个非套接字上尝试了一个操作";
break;
case WSAEADDRINUSE:
strError = "特定的地址已在使用中";
break;
case WSAECONNRESET:
strError = "与主机的连接被关闭";
break;
default:
strError = "一般错误";
}
return strError;

}

int CtraDlg::GetLocalHostName(CString &sHostName) //获得本地计算机名称
{
char szHostName[256];
int nRetCode;
nRetCode = gethostname(szHostName,sizeof(szHostName));
if(nRetCode!=0)
{
//产生错误
sHostName = _T("获取不到主机名!");
return GetLastError();
}
sHostName = szHostName;
return 0;
}

int CtraDlg::GetIpAddress(const CString &sHostName, CString &sIpAddress)//获得本地IP
{
struct hostent FAR * lpHostEnt=gethostbyname(sHostName);
if(lpHostEnt==NULL)
{
//产生错误
sIpAddress = _T("");
return GetLastError();
}
//获取IP
LPSTR lpAddr = lpHostEnt->h_addr_list[0];
if(lpAddr)
{
struct in_addr inAddr;
memmove(&inAddr, lpAddr, 4);
//转换为标准格式
sIpAddress = inet_ntoa(inAddr);
if (sIpAddress.IsEmpty())
{
sIpAddress = _T("获取不到IP!");
}
}
return 0;
}

int CtraDlg::GetNamebyAddress(const CString &IpAddress,CString &sYouName)//获得对方计算机名称
{
unsigned long addr;
addr = inet_addr(IpAddress);
struct hostent FAR * lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL)
{
//产生错误
sYouName = _T("");

AfxMessageBox("无法连接!");//应该取得其错误
return -1;
}
CString name = lpHostEnt->h_name;
sYouName = name;
return 0;

}

void CtraDlg::OnRadioServer()
{
// TODO: Add your control notification handler code here
CString text;
if (m_nSockType == SOCK_TCP)
{
text = "TCP方式";
}
else
{
text = "UDP方式";
}
m_server = 1;
m_client = 2;
m_WorkType = 0;
SetWindowText("服务器 " + text);
GetDlgItem(IDC_BUTTON_CONNECT)->SetWindowText("启动服务");
GetDlgItem(IDC_BUTTON_DISCONNECT)->SetWindowText("关闭服务");

}

void CtraDlg::OnRadioClient()
{
// TODO: Add your control notification handler code here
CString text;
if (m_nSockType == SOCK_TCP)
{
text = "TCP方式";
}
else
{
text = "UDP方式";
}
m_server = 2;
m_client = 1;
m_WorkType = 1;
SetWindowText("客户端 " + text);
GetDlgItem(IDC_BUTTON_CONNECT)->SetWindowText("连接");
GetDlgItem(IDC_BUTTON_DISCONNECT)->SetWindowText("断开连接");

}

void CtraDlg::OnRadioBoth()
{
// TODO: Add your control notification handler code here
CString text;
if (m_nSockType == SOCK_TCP)
{
text = "TCP方式";
}
else
{
text = "UDP方式";
}
m_server = m_client = 0;
m_WorkType = 2;
SetWindowText(text);
GetDlgItem(IDC_BUTTON_CONNECT)->SetWindowText("启动");
GetDlgItem(IDC_BUTTON_DISCONNECT)->SetWindowText("关闭");
}

void CtraDlg::OnButtonStopFile()
{
// TODO: Add your control notification handler code here
FileStop = true;
FileWork = false;
GetDlgItem(IDCANCEL)->EnableWindow(true);
GetDlgItem(IDC_BUTTON_DISCONNECT)->EnableWindow(true);
}

LRESULT CtraDlg::OnKSend(WPARAM wParam,LPARAM lParam)
{
OnButtonSendMsg();
return 0;
}


BOOL CtraDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN)
{
if (GetFocus()->GetDlgCtrlID()==IDC_EDIT_SENDMSG || GetFocus()->GetDlgCtrlID()==IDC_BUTTON_SEND_MSG)
{
AfxGetMainWnd()->SendMessage(WM_KSEND);
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// traDlg.h : header file
//

#if !defined(AFX_traDLG_H__F42FE5AC_E2CC_44AB_9D0A_748191BC989F__INCLUDED_)
#define AFX_traDLG_H__F42FE5AC_E2CC_44AB_9D0A_748191BC989F__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

//#include "ColorListBox.h"
/////////////////////////////////////////////////////////////////////////////
// CtraDlg dialog

class CtraDlg : public CDialog
{
// Construction
public:
CtraDlg(CWnd* pParent = NULL); // standard constructor

// Dialog Data
//{{AFX_DATA(CtraDlg)
enum { IDD = IDD_tra_DIALOG };
CProgressCtrl m_Progress;
CListBox m_AddMsgLIst;
CIPAddressCtrl m_You_IP;
CString m_MsgSend;
//}}AFX_DATA

// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CtraDlg)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL

// Implementation
protected:
HICON m_hIcon;

// Generated message map functions
//{{AFX_MSG(CtraDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnButtonConnect();
afx_msg void OnButtonDisconnect();
afx_msg void OnButtonSendMsg();
afx_msg void OnButtonSendFile();
afx_msg void OnButtonClear();
afx_msg void OnRadioTcp();
afx_msg void OnRadioUdp();
afx_msg void OnRadioServer();
afx_msg void OnRadioClient();
afx_msg void OnRadioBoth();
afx_msg void OnButtonStopFile();
afx_msg LRESULT OnKSend(WPARAM wParam,LPARAM lParam);//发送消息
//afx_msg void OnButtonCaputer();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()

public:
int SaveYouFile(CSocket &recSo,SOCKADDR_IN &client);
int ReceiveFileMsg(CSocket & socket,SOCKADDR_IN &client);
int GetIpAddress(const CString & sHostName,CString & sIpAddress);
int GetLocalHostName(CString &sHostName);
CString GetError(DWORD error);
int m_nSockType; //连接类型
int m_WorkType; //工作方式 server0,client1,both2
void AddMsgList(CString IP, CString str); //LISTBOX控件添加信息
int m_client, m_server;
CString m_fileName;
bool FileWork, FileStop, StopServer;
char m_type;//接受类型/F-文件,C-抓平,D-关闭,M-消息
int m_Potr;//当前使用端口
int GetNamebyAddress(const CString &IpAddress,CString &sYouName);//获得对方计算机名称

};
struct FILEINFO
{
int fileLength;
char fileName[100];

};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_traDLG_H__F42FE5AC_E2CC_44AB_9D0A_748191BC989F__INCLUDED_)

参考资料

网上的资料,查到的大部分都是用的MFC的socket类做的……

高级版→→→→
1.基于MFC仿QQ聊天程序设计完整实例教程
2.CRichEditCtrlEx支持静态表情聊天类的使用

文章目录
  1. 1. 初级版
  2. 2. 中级版
    1. 2.1. 界面
  3. 3. 参考资料
|