Windows Socket 编程 : 支持多线程(TCP)(环境:VS2010)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Windows Socket 编程:支持多线程(TCP)(环境:VS2010)几点说明:
(1)发送的数据不能有空格;
(2)这是控制台应用程序;
1、UserMesInfo.h 公共文件,客户端和服务器端公用;
1 #ifndef User_Mes_Sock
2#define User_Mes_Sock
3 #include
4#endif
5
6const short MesLogin = 1001;
7const short MesError = 1002;
8const short MesNormal = 1003;
9const short LoginSuc = 1004;
10const short MesToAll = 1005;
11const short OnLineUser = 1010;
12
13
14//User Struct
15struct UserInfo
16 {
17short userId;
18char userName[32];
19 SOCKET userSock;
20 LONG userAddr;
21 UserInfo *pNext;
22 };
23
24//Message Struct
25struct MesInfo
26 {
27short MesType;
28char fromUserName[32]; 29char toUserName[32]; 30char MesContent[1024];
31 };
2、TCP:客户端程序
1 #include
2 #include
3 #include
4
5 #include "UserMesInfo.h"
6
7#pragma comment(lib,"ws2_32.lib")
8
9using namespace std;
10
11 BOOL isLogin = false;
12
13
14string charToString(char temp[])
15 {
16string tempStr = "";
17for(int i = 0; i < sizeof(temp); i++) 18 tempStr += temp[i];
19return tempStr;
20 }
21
22 BOOL SendMes(SOCKET servSocket)
23 {
24 SOCKET servSock = servSocket;
25while(TRUE)
26 {
27int tempWho;
28char sendBuff[1024] = {0};
29if(isLogin)
30 {
31 printf("'1' : speak to ONE ;\n '2' : speak to ALL ;\n '3' : OnLine Users ; \n '4' : Exit ;\n");
32
33 cin>>tempWho;
34 }
35if( isLogin && tempWho == 1)
36 {
37//To One
38 printf("Please input NAME you want to CHAT : ");
39char toName[32] = {0};
40 scanf("%s", toName);
41 memcpy(sendBuff, &MesNormal, 2);
42 memcpy(sendBuff+2, toName, 32);
43 printf("Please input what do you want to say : ");
44char Message[1000] = {0};
45 scanf("%s", Message);
46 memcpy(sendBuff+34, Message, strlen(Message));
47 send(servSock, sendBuff, sizeof(sendBuff)+1, 0);
48 } else if(isLogin && tempWho == 2){
49//To ALL
50 printf("Please input DATA : ");
51char Message[1000] = {0};
52 scanf("%s", Message);
53
54 memcpy(sendBuff, &MesToAll, 2);
55 memcpy(sendBuff+2, Message, strlen(Message));
56 send(servSock, sendBuff, sizeof(sendBuff)+1, 0);
57
58 } else if(isLogin && tempWho == 3){
59char getOnLineUsers[4];
60 memcpy(getOnLineUsers, &OnLineUser, 2);
61 send(servSock, getOnLineUsers, sizeof(getOnLineUsers), 0);
62 } else if(isLogin && tempWho == 4){
63break;
64 } else if(isLogin){
65 printf("You input Error! Please Again !");
66 }
67