Windows Socket 編程:支持多線程(TCP)(環(huán)境:VS2010)_第1頁(yè)
Windows Socket 編程:支持多線程(TCP)(環(huán)境:VS2010)_第2頁(yè)
Windows Socket 編程:支持多線程(TCP)(環(huán)境:VS2010)_第3頁(yè)
Windows Socket 編程:支持多線程(TCP)(環(huán)境:VS2010)_第4頁(yè)
Windows Socket 編程:支持多線程(TCP)(環(huán)境:VS2010)_第5頁(yè)
已閱讀5頁(yè),還剩24頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

WindowsSocket編程:支持多線程(TCP(環(huán)境:VS2010)幾點(diǎn)說(shuō)明:(1)發(fā)送的數(shù)據(jù)不能有空格;(2)這是控制臺(tái)應(yīng)用程序;1、UserMesInfo.h公共文件,客戶端和服務(wù)器端公用;#ifndefUserMesSock#defineUser_Mes_Sock#include<winsock2.h>#endif56constshortMesLogin=1001;7constshortMesError=1002;8constshortMesNormal=1003;9constshortLoginSuc=1004;10constshortMesToAll=1005;11constshortOnLineUser=1010;

//UserStruct141516171819202122232425262728293031希2、structUserInfo{shortcharSOCKETLONGUserInfouserId;userNam32];userSock;userAddr;*pNext;};//MessageStructstructMesInfo{shortMesType;charfromUserNam32];chartoUserNam32];charMesConten1024];};TCP:客戶端程序234567891011121314151617181920211#include<iostream>#include<stdlib.h>#include<WinSock2.h〉#include"UserMesInfo.h"#pragmacomment(lib,"ws2_32.lib")usingnamespacestd;BOOLisLogin=false;stringcharToString(chartemp[]){stringtempStr="";for(inti=0;i<sizeof(temp);tempStr+=temp[i];returntempStr;22232425262728293031'3'32333435363738394041424344BOOLSendMes(SOCKETservSocket){SOCKETservSock=servSocket;while(TRUE){inttempWho;charsendBuff[1024]={0};if(isLogin){print"('1' :speaktoONE;\n'2' :speaktoALL;\n:OnLineUsers;\n'4' :Exit;\n");cin〉〉tempWho;}if(isLogin&&tempWho==1){//ToOneprint"PleaseinputNAMEyouwanttoCHAT:"chartoName[32]={0};scan"%s",toName);memcpy(sendBuff,&MesNormal2);memcpy(sendBuf2,+toName,32);print"Pleaseinputwhatdoyouwanttosay:charMessage[1000]={0};45464748495051525354555657585960610);626364656667scan"%s",Message);memcpy(sendBuf34,Message,strlen(Message));send(servSock,sendBuffsizeof(sendBuff)+1,0);elseif(isLogin&&tempWho==2){//ToALLprint"PleaseinputDATA:");charMessage[1000]={0};scan"%s",Message);memcpy(sendBuff,&MesToAll2);memcpy(sendBuf2:+Message,strlen(Message));send(servSock,sendBuffsizeof(sendBuff)+1,0);elseif(isLogin&&tempWho==3){chargetOnLineUsers[4];memcpy(getOnLineUsers,&OnLineUser2);send(servSocJgetOnLineUsers,sizeof(getOnLineUsers),elseif(isLogin&&tempWho==4){break;elseif(isLogin){print"YouinputError!PleaseAgain!");6869707172737475767778798081828384858687888990returnTRUE;}DWORDWINAPIProcThread(LPVOIDlpParameter){SOCKETcliSocket=*(SOCKET*)lpParameter;//SOCKADDR_INsockFrom;//intlength=sizeof(SOCKADDR);charrecvBuf[1024]={0};while(true){memset(recvBuf0x00,1024);intrecvLen=recv(cliSocket,recvBuf,1024,0);if(recvLen>0){shortmegId=*(short*)recvBuf;switch(megId)919293949596979899100101102103104105106107108109110111112113caseLoginSuc:{//charuserName[32]={0};//memcpy(userName,recvBuf+2,4);pri"LoginSuccess!\n");isLogitrue;}break;caseMesNormal:{charMess[1000];memcpy(Mess,recv2jfsizeof(recvBuf)-2);pri"t==>Me:%s\n",Mess);}break;caseMesToAll:{charMess[1000];memcpy(Mess,recv2jfsizeof(recvBuf)-2);pri"t==>All:%s\n",Mess);break;114115116117118sizeof119120121122123124125126127128129130131132133134135caseOnLineUser:{charonLineUser[100]={0};memcpy(onLineUser,recvBuf+2,(recvBuf)-2);//stringuserStr=charToString(onLineUser);for(inti=0;i<sizeof(onLineUser);i++)cout<<onLineUser[i];//printf(”%s\n",userStr);cout<<endl<<onLineUser<<endl;printfi");}break;default:break;}//endif//endwhile

return0;}intmain(){WORDwVersionRequested;WSADATAwsaData;interr;wVersionRequested=MAKEW0RD2,2);err=WSAStartup(wVersionRequested,&wsaData);TOC\o"1-5"\h\zif(err!=0) {print"WSAStartupfailedwitherror:%d\n",err);return1;if(LOBYTE(wsaData.wVersion)!= 2 ||HIBYTE(wsaData.wVersion)!=2) {136137138139140141142143144145146147148149150151152153154155/*Telltheuserthatwecouldnotfindausable*/156/*WinSockDLL.*/155/*Telltheuserthatwecouldnotfindausable*/156/*WinSockDLL.*/157157print"CouldnotfindausableversionofWinsock.dll'n");158159160161162163164165166167168169170171172173174175176177178179sizeofWSACleanup();return1;}elseprint"TheWinsock2.2dllwasfoundokay\n");SOCKETclientSock=socket(AF_INET,SOCK_STREAM,0);if(clientSock==-1){perro"socket創(chuàng)建出錯(cuò)!");exifLO;}SOCKADDR_INaddrClient;addrClient.sin_addr.S_un.S_addr=inet_addr"127.0.0.1");addrClient.sin_family=AF_INET;addrClient.sin_port=htons6000);intret(SOCKADDR));intret(SOCKADDR));180if(ret)181{182print"連接失敗\n");183return-1;184}185186HANDLEthHandle=CreateThread(NULL,0,ProcThread,&clientSock,0,NULL);187188if(NULL==thHandle)189{190cout"CreateThreadfailed!"<<endl;191return-1;192}193194charuserName[32];195printf"Pleaseinputname:");196scanfs"%s",userName,31);197198/*199UserInfo*user=newUserInfo;200user->userSock=clientSock;201strcpys(user-〉userName,userName);

202203204205206207208209210211212213214215216217218219220221222223user-〉userAddr=addrClient.sinaddr.Sun.Saddr;*/charloginInfo[64]={0};memcpy(loginInfo,&MesLogin,2);memcpy(loginInfo2,userName,strlen(userName));//inta=send(clientSock,loginInfo,strlen(loginInfo),0);inta=send(clientSock,loginInfo,strlen(loginInfo),0);SendMes(clientSock);//Sleep(20000);//closesocket(clientSock);CloseHandle(thHandle);WSACleanup();system"PAUSE");return0;

3、TCP:服務(wù)器端程序#include<iostream>#include<cstdlib>#include<winsock2.h〉#include<string>#include<Windows.h>#include"UserMesInfo.h"7#pragmacomment(lib,"ws2_32.lib")9usingnamespacestd;11UserInfo*gUserInfo;13stringcharToString(chartemp[]){stringtempStr="";

for(inti=0;i<sizeof(temp);i++)tempStr+=temp[i];returntempStr;}DWORDWINAPIProcMes(LPVOIDlpParameter){SOCKETcliSocket=((UserInfo*)lpParameter)-〉userSock;//SOCKADDR_INsockFrom;charrecvBuf[1024];//intlength=sizeof(SOCKADDR);while(true)memset(recvBuf0x00,1024);recv(cliSocket,recvBuf1024,0);shortMesType=*(short*)recvBuf;17181920212223242526272829303132333435363738switch(MesType)4142434445464748((UserInfo*)495051525354555657585940case40caseMesLogin:{staticshortUSERID=1001;UserInfo*userInfonewUserInfo;char*userName=(char*)(recvBuf+2);strcpy_s(userInfo-〉userName,userName);userInfo->userId=USERID++;userInfo-〉userSock=cliSocket;userInfo->userAddr=lpParameter)->userAddr;userInfo->pNext=NULL;if(!gUserInfo){gUserInfo=userInfo;else{userInfo->pNext=gUserInfo;gUserInfo=userInfo;}printf("Login: %s==>%d!\n",userInfo-〉userName,userInfo-〉userId);65666768697071727374757677787980818262memcpy(loginInfo,&LoginSu2);6362memcpy(loginInfo,&LoginSu2);6364inti=send(cliSocket,logininfo,strlen(loginlnfo),0);}break;caseMesNormal:{//printf("TheNormalMessage!");chartoName[32]={0};memcpy(toName,recvB2f+32);cout<<toName<<endl;charMessage[1000]={0};memcpy(Message,recvB34+sizeof(recvBuf)-34);print%s\n",Message);charsendMes[1006];memcpy(sendMes,&MesNorma2);memcpy(sendM2s+^ecvBuf+34,sizeof(recvBuf)-34);//send(toSock,sendMes,sizeof(sendMes),0);838485868788strlen(toName)8990910);9293949596979899100101UserInfo*tempUser=gUserInfo;BOOLsendFlagfalse;while(tempUser){if(!memcmp(toName,tempUser-〉userName,)){SOCKETtoSock=tempUser-〉userSock;send(toSock,sendMes,strlen(sendMes1+sendFlatrue;}tempUser=tempUser-〉pNext;}if(!sendFlag){printSfendFailed!\n");}102break;102103caseMesToAll:103caseMesToAll:105charMessage[1000]={0};106memcpy(Message,recvB2f+sizeof(recvBuf)-2);107UserInfo*tempUser=gUserInfo;108charsendMes[1002];109memcpy(sendMes,&MesToAl2);110memcpy(sendM2,+Message,sizeof(Message));111while(tempUser)112{113SOCKETtoSock=tempUser-〉userSock;1140);inti=send(toSock,sendMes,strlen(sendMes)+1,126case126caseOnLineUser:115if(i>0)116{117printf( "SendTo%sSuccess!\n",tempUser-〉userName);118}119tempUser=tempUser-〉pNext;120}121}122break;123caseMesError:124//printf("TheErrorMessage!");125break;

128129charonLineUserBuff[1000]={0};130UserInfo*tempUser=gUserInfo;131132memcpy(onLineUserBuff,&OnLineUse2);133134inti=0;135stringuserStr="";136while(tempUser)137{138userStr+=charToString(tempUser-〉userName);139//處理方式有問(wèn)題14032);//memcpy(onLineUserBuff+2,tempUser-〉userName,141//send(cliSocket,onLineUserBuff,sizeof(onLineUserBuff),0);142tempUser=tempUser-〉pNext;143}144memcpy(onLineUserBuff+2,userStr.cstr(),userStr.length());send(cliSocket,onLineUserBuff,sizeof(onLineUserBuff),0);146148149150151152153154155156157158159160161162163164165166167168169break;default://printf("TheDefaultProcessbreak;}return0;}intmain(){WORDwVersionRequested;WSADATAwsaData;interr;wVersionRequested=MAKEWORD2,2);&wsaData);err=WSAStartup(wVersionRequested,

print"WSAStartupfailedwitherror:%d\n"&wsaData);return1;if(LOBYTE(wsaData.wVersion)!= 2(wsaData.wVersion)!=2) {/*Telltheuserthatwecouldnotfindausable*/*//*WinSockDLL.*/print"CouldnotfindausableversionofWinsock.dll'n");WSACleanup();return1;}elseprint"TheWinsock2.2dllwasfoundokay\n");SOCKETservSock=socket(AF_INET,SOCK_STREAM,0);SOCKADDR_INaddrServ;addrServ.sin_family=AF_INET;170171172173174HIBYTE175176177178179180181182183184185186187188189190191addrServ.sin_port=htons6000);addrServ.sinaddr.Sun.Saddr=htonl(INADDRANY);192bind(servSock,(SOCKADDR*)&addrServ,sizeof(SOCKA

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論