版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
知識(shí)影響格局,格局決定命運(yùn)!TCPIP協(xié)議與網(wǎng)絡(luò)編程期末大作業(yè)編號(hào)TCP/IP協(xié)議與網(wǎng)絡(luò)編程期末大作業(yè)題目:基于Socket的網(wǎng)絡(luò)通信物聯(lián)網(wǎng)工程學(xué)院計(jì)算機(jī)科學(xué)與技術(shù)專業(yè)學(xué)號(hào)學(xué)生姓名任課教師二〇一六年X月摘要課題是基于TCP/UDP室系統(tǒng)主要包括注冊(cè)、登陸、群聊、單聊、顯示在線人員和退出功能。系統(tǒng)于TCP協(xié)議,服務(wù)器端向客戶顯示端發(fā)送數(shù)據(jù)是基于UDP協(xié)議。接字,達(dá)到數(shù)據(jù)傳送的目的,從而實(shí)現(xiàn)聊天室系統(tǒng)功能。關(guān)鍵詞:TCP/UDP;聊天室;網(wǎng)絡(luò)套接字;數(shù)據(jù)傳送目錄第1章總體設(shè)計(jì)2第2章客戶端設(shè)計(jì)32.1發(fā)送端設(shè)計(jì)32.11流程圖32.12代碼32.2接收端設(shè)計(jì)32.21流程圖32.22代碼3第3章服務(wù)器設(shè)計(jì)43.1流程圖43.2代碼4第4章運(yùn)行結(jié)果5第1章總體設(shè)計(jì)1原理1.1TCPTCP/IP協(xié)議的程序是傳輸層使用TCP器之間先建立連接,在數(shù)據(jù)傳輸完成后要關(guān)閉連接,釋放網(wǎng)絡(luò)資源。面向連接的客戶/服務(wù)器程序工作模型如下:1.2UDP無(wú)連接的數(shù)據(jù)報(bào)(SOCK_DGRAM)傳輸服務(wù)在傳輸層使用的協(xié)議時(shí)UDP協(xié)只要關(guān)閉套接口,釋放網(wǎng)絡(luò)資源,通信過(guò)程就結(jié)束了。無(wú)連接的數(shù)據(jù)包傳輸服務(wù)通信是,客戶端與服務(wù)器端所使用的函數(shù)是類似的。面向無(wú)連接的客戶/服務(wù)器程序工作模型如下:1.3流程圖基于TCP/UDP分。功能主要是注冊(cè)、登陸、群聊、單聊、顯示在線人員和退出??蛻舳伺c1知識(shí)影響格局,格局決定命運(yùn)!服務(wù)器端的連接協(xié)議基于TCPUDP端與服務(wù)器端建立連接后,客戶端進(jìn)行操作,將數(shù)據(jù)發(fā)送至客戶顯示端。第2章客戶端設(shè)計(jì)2.11流程圖2.12代碼#includewinsock2.h#includestdlib.h#includestdio.h#pragmacomment(lib,“Ws2_32.lib“)#defineBUFFER_SIZE1024voidMySendMessage(SOCKETsSocket,char*response,intresponseLen);intmain(intargc,char**argv){WSADATAwsaData;sockaddr_inser,cli;SOCKETsClient,wchysClient;intiLen,wchyiLen;intiRecv;charsend_buf[1000];charrecv_buf[BUFFER_SIZE];if(WSAStartup(MAKEWORD(2,2),wsaData)!=0){printf(“WSAStartup()\n“);return0;}printf(“手動(dòng)連接模式中....\n“);charszServer[256];//連接的服務(wù)器地址,IP地址printf(“請(qǐng)輸入即將連接的服務(wù)器IP地址:“);gets(szServer);ser.sin_family=AF_INET;ser.sin_port=htons(5050);ser.sin_addr.s_addr=inet_addr(szServer);charuser[20],password[20];charstr[100],str1[100],wchystr[100];boolhasLogin=false;//只能綁定一次,開(kāi)始放在了循環(huán)里,555wchysClient=socket(AF_INET,SOCK_DGRAM,0);if(wchysClient==INVALID_SOCKET){printf(“socket()Faild:%d\n“,WSAGetLastError());return0;}cli.sin_family=AF_INET;cli.sin_port=htons(5053);cli.sin_addr.s_addr=htonl(INADDR_ANY);if(bind(wchysClient,(LPSOCKADDR)cli,sizeof(cli))==SOCKET_ERROR){printf(“bind()Faild:%d\n“,WSAGetLastError());return0;}wchyiLen=sizeof(cli);memset(recv_buf,0,sizeof(recv_buf));sClient=socket(AF_INET,SOCK_STREAM,0);if(sClient==INVALID_SOCKET){printf(“socket()\n“);return0;}if(connect(sClient,(sockaddr*)ser,sizeof(ser))==INVALID_SOCKET){printf(“socket()\n“);return0;}else{boolhasLogin=false;while(!hasLogin){printf(“--------------------------------\n“);printf(“0.注冊(cè)\2知識(shí)影響格局,格局決定命運(yùn)!n“);printf(“1.登陸\n“);printf(“2.退出\n“);printf(“請(qǐng)輸入相應(yīng)的數(shù)字:\nscanf(“%s“,str);switch(str[0]){case'0':printf(“用戶名:“);scanf(“%s“,user);printf(“密碼:“);scanf(“%s“,password);strcpy(send_buf,“0“);strcat(send_buf,user);strcat(send_buf,“@“);strcat(send_buf,password);MySendMes戶名:“);scanf(“%s“,user);printf(“密碼:“);scanf(“%s“,password);strcpy(send_buf,“1“);strcat(send_buf,user);strcat(send_buf,“@“);strcat(send_buf,password);MySendMessage(sClient,send_buf,sizeof(send_buf));iRecv=recvfrom(wchysClient,recv_buf,BUFFER_SIZE,0,(SOCKADDR*)cli,wchyiLen);if(iRecv==SOCKET_ERROR){printf(“recvfrom()Faild:%d\n“,WSAGetLastError());return0;}elseif(iRecv==0)break;else{//接收到了正確數(shù)據(jù)recv_buf[1]=='@'){hasLogin=0;system(“cls“);printf(“登錄失?。?'){hasLogin=0;system(“cls“);printf(“已經(jīng)在其他地方登陸\n“);printf(“登錄失??!請(qǐng)重新選擇用戶登錄或注冊(cè)后登錄^_^\n“);}if(recv_buf[0]=='#'recv_buf[1]=='#'){hasLogin=1;system(“cls“);printf(“登錄成功^_^\n“);boolwchyhasLogin=false;while(!wchyhasLogin){printf(“--------------------------------\n“);printf(“0.群聊\n“);printf(“1.單聊\n“);printf(“2.在線用戶\n“);printf(“3.退出\n“);printf(“請(qǐng)輸入相應(yīng)的數(shù)字:\nscanf(“%s“,wchystr);switch(wchystr[0]){case'0':wchyhasLogin=1;printf(“輸入exit退出。\n“);printf(“--------------------------------\n“);while(wchyhasLogin){printf(“scanf(“%s“,str);if(strcmp(str,“exit“)!=0){strcpy(send_buf,“2“);strcat(send_buf,user);strca3知識(shí)影響格局,格局決定命運(yùn)!t(send_buf,“@“);strcat(send_buf,str);MySendMessage(sClient,send_buf,sizeof(send_buf));}else{system(“cls“);wchyhasLogin=0;}}break;case'1':wchyhasLogin=1;printf(“請(qǐng)輸入單聊對(duì)象的用戶名:“);scanf(“%s“,str1);strcpy(send_buf,“5“);strcat(send_buf,str1);strcat(send_buf,“@“);strcat(send_buf,user);strcat(send_buf,“*“);strcat(send_buf,“__Welcome__To__Single__Chat...“);MySendMessage(sClient,send_buf,sizeof(send_buf));iRecv=recvfrom(wchysClient,recv_buf,BUFFER_SIZE,0,(SOCKADDR*)cli,wchyiLen);if(iRecv==SOCKET_ERROR){printf(“recvfrom()Faild:%d\n“,WSAGetLastError());return0;}elseif(iRecv==0)break;else{//接收未在線,退出了單聊模式\n“);}if(recv_buf[0]=='%'recv_buf[1]=='%'){printf(“輸入exit退出。\n“);printf(“--------------------------------\n“);while(wchyhasLogin){printf(“scanf(“%s“,str);if(strcmp(str,“exit“)!=0){strcpy(send_buf,“5“);strcat(send_buf,str1);strcat(send_buf,“@“);strcat(send_buf,user);strcat(send_buf,“*“);strcat(send_buf,str);MySendMessage(sClient,send_buf,sizeof(send_buf));}else{system(“cls“);wchyhasLogin=0;}}}break;case'2':strcpy(send_buf,“4“);strcat(send_buf,user);strcat(send_buf,“@“);strcat(send_buf,str);MySendMessage(sClient,send_buf,sizeof(send_buf));system(“cls“);break;case'3':strcpy(send_buf,“3“);strcat(send_buf,user);strcat(send_buf,“@“);MySendMessage(sClient,send_buf,sizeof(send_buf));hasLogin=0;wchyhasLogin=1;system(“cls“);break;default:system(“cls“);printf(“請(qǐng)輸入正確信息\n“);break;}}}break;case'4知識(shí)影響格局,格局決定命運(yùn)!2':exit(0);break;default:system(“cls“);printf(“請(qǐng)輸入正確信息“);}}}system(“PAUSE“);closesocket(sClient);WSACleanup();return0;}voidMySendMessage(SOCKETsSocket,char*response,intresponseLen){intiSend;iSend=send(sSocket,response,responseLen,0);if(iSend==SOCKET_ERROR){printf(“send()Failed.:%d\n“,WSAGetLastError());}elseif(iSend==0);else{//printf(“send()succeeded!\n“);printf(“----------------------\n“);}}2.2接收端設(shè)計(jì)2.21流程圖2.22代碼#includestdlib.h#includestring.h//formain.cpp(1.cpp)#defineDEFAULT_PORT5051//FORRECV#defineDEFAULT_PORTSEND5052//FORSEND#defineBUFFER_LENGTH1000constboolDebug=0;#defineMaxUser1000//--------------------------------------------------------------------------------////當(dāng)程序遇到異常而結(jié)束時(shí)會(huì)示出錯(cuò)誤而退出//--------------------------------------------------------------------------------////成員結(jié)構(gòu)信息#defineUserNameLen200#definePasswordLen200typedefstruct{charUserName[200];charPassword[200];boolLog;//是否登陸charIp[20];}UserData;#definethefile“config.txt“boolSaveData(UserData**userdata,intuserdatap);//--------------------------------------------------------------------------------////初始化用戶數(shù)據(jù)導(dǎo)入intfindUser(UserData**data,intnum,char*name){inti;for(i=0;i=num;i++){if(strcmp(name,data[i]-UserName)==0)returni;}return-1;}voiddeal(char*str,UserData**data,intnum,char*response,char*ip){charUser[UserNameLen];charPass[PasswordLen];//第一位字符是功能號(hào)//0注冊(cè)//1登陸//2會(huì)話//3退出0+name+@+passwordfor(i=1;istrlen(str);i++)if(str[i]=='@')break;str[i]='\0';strcpy(User,str+1);strcpy(Pass,str+i+1);t=findUser(data,num,U5知識(shí)影響格局,格局決定命運(yùn)!ser);if(t==-1){//該用戶名不存在,可以注冊(cè)num++;data[num]=(UserData*)malloc(sizeof(UserData));if(data[num]==NULL){printf(“[+]ERROR:mallocfailed\n“);exit(1);}strcpy(data[num]-UserName,User);strcpy(data[num]-Password,Pass);data[num]-Log=0;memset(data[num]-Ip,'\0',sizeof(data[num]-Ip));printf(“%s用戶注冊(cè)成功\n“,User);//--------------------------------------------------注冊(cè)完成//返回成功信息strcpy(response,“00“);//第一位是功能號(hào)第二位是狀態(tài)號(hào)0表示成功1表示失敗SaveData(data,num);}else{//failprintf(“%s用戶注冊(cè)失?。躰“,User);//-----------------------------------------------注冊(cè)失敗strcpy(response,“01“);}}elseif(str[0]=='1'){//登陸的消息格式為1+name+@+passwordfor(i=1;istrlen(str);i++)if(str[i]=='@')break;str[i]='\0';//printf(“i=%d\n“,i);strcpy(User,str+1);strcpy(Pass,str+i+1);t=findUser(data,num,User);if(t!=-1){//找到該用戶//printf(“Pass=%s“,Pass);//printf(“Pawd=%s“,data[t]-Password);if(strcmp(Pass,data[t]-Password)==0data[t]-Log==0){//密碼驗(yàn)證成功printf(“%s登陸成功\n“,User);data[t]-Log=1;strcpy(data[t]-Ip,ip);strcpy(response,“10“);}elseif(strcmp(Pass,data[t]-Password)==0data[t]-Log==1){printf(“%s已經(jīng)在其他地方登陸\n“,User);strcpy(response,“1@“);}else{printf(“%s登陸密碼錯(cuò)誤\n“,User);strcpy(response,“11“);}}else{printf(“%s用戶不存在,登陸失?。躰“,User);strcpy(response,“12“);}}elseif(str[0]=='2'){//會(huì)話的消息格式為2+'name'+'@'+'(message)'for(i=1;istrlen(str);i++)if(str[i]=='@')break;str[i]='\0';strcpy(User,str+1);t=findUser(data,num,User);if(t!=-1strcmp(data[t]-UserName,User)==0strcmp(data[t]-Ip,ip)==0){//表示確實(shí)是正6知識(shí)影響格局,格局決定命運(yùn)!確用戶發(fā)來(lái)的會(huì)話strcpy(response,“20“);strcat(response,User);strcat(response,“:“);strcat(response,str+i+1);printf(“%s:%s\n“,User,str+i+1);}else{strcpy(response,“21“);printf(“非正確用式為@')break;str[i]='\0';strcpy(User,str+1);t=findUser(data,num,User);if(t!=-1strcmp(data[t]-UserName,User)==0strcmp(data[t]-Ip,ip)==0){//表示確實(shí)是正確用戶發(fā)來(lái)的會(huì)話strcpy(response,“30“);data[t]-Log=0;memset(data[t]-Ip,'\0',sizeof(data[t]-Ip));printf(“%s退出\n“,data[t]-UserName);}else{strcpy(response,“31“);printf(“非正確用戶發(fā)來(lái)會(huì)話,不予處理!“);}}elseif(str[0]=='4'){for(i=1;istrlen(str);i++)if(str[i]=='@')break;str[i]='\0';strcpy(response,“40“);for(i=0;i=num;i++){if(data[i]-Log==1){printf(“%s[%s]在線\n“,data[i]-UserName,data[i]-//printf(“%s\n“,data[i]-UserName);strcat(response,data[i]-UserName);strcat(response,““);}else{//printf(“%s“,data[i]-}}}elseif(str[0]=='5'){for(i=1;istrlen(str);i++)if(str[i]=='@')break;str[i]='\0';strcpy(User,str+1);printf(“%s用戶接收\n“,User);strcpy(Pass,str+i+1);for(i=1;istrlen(Pass);i++)if(Pass[i]=='*')break;Pass[i]='\0';printf(“%s用戶發(fā)送\n“,Pass);t=findUser(data,num,User);if(t==-1){strcpy(response,“60“);printf(“單聊對(duì)象不存在“);}else{if(data[t]-Log==0){strcpy(response,“61“);printf(“%s未在線\n“,User);}elseif(data[t]-Log==1){strcpy(response,“50“);strcat(7知識(shí)影響格局,格局決定命運(yùn)!response,Pass);strcat(response,“:“);strcat(response,Pass+i+1);printf(“%s:%s\n“,Pass,Pass+i+1);printf(“%s在線,可進(jìn)行聊天\n“,User);}}}}voidMySendMessage(intsSocket,char*response,intresponseLen,SOCKADDR*cli,intcliLen){intiSend;iSend=sendto(sSocket,response,responseLen,0,(SOCKADDR*)cli,cliLen);if(iSend==SOCKET_ERROR){printf(“sendto()Failed.:%d\n“,WSAGetLastError());}elseif(iSend==0);else{//printf(“sendto()succeeded!\n“);//printf(“----------------------\n“);}}boolInitData(UserData**s,intnum,intp)//成功返回true發(fā)生錯(cuò)誤返回false{//-----------------------------------------////讀取文件信息并返回FILE*fp;charUserBuf[UserNameLen];charPassBuf[PasswordLen];fp=fopen(thefile,“r“);if(!fp){if(Debug)printf(“config文件不存在\n“);}else{if(Debug)printf(“findconfig.txt\n“);while(!feof(fp)){//fgets(buf,sizeof(buf),fp);fscanf(fp,“%s“,UserBuf);fscanf(fp,“%s“,PassBuf);if(Debug)printf(“[+]User:%sPassword:%s\n“,UserBuf,PassBuf);//addp++;s[p]=(UserData*)malloc(sizeof(UserData));if(!s[p]){printf(“[+]ERROR:mallocfailed!\n“);returnfalse;}strcpy(s[p]-UserName,UserBuf);strcpy(s[p]-Password,PassBuf);s[p]-Log=0;memset(s[p]-Ip,'\0',sizeof(s[p]-Ip));}fclose(fp);}returntrue;}boolSaveData(UserData**userdata,intuserdatap){FILE*fp;///建立配置文件fp=fopen(thefile,“w“);if(!fp){printf(“[+]ERROR:無(wú)法創(chuàng)建config文件!“);returnfalse;};inti;for(i=0;i=userdatap;i++){fprintf(fp,“%s%s“,userdata[i]-UserName,userdata[i]-Password);if(i!=userdatap)fprintf(fp,“\n“);}fclose(fp);}#includewinsock2.h#includestdlib.h#includestdio8知識(shí)影響格局,格局決定命運(yùn)!.h#pragmacomment(lib,“ws2_32.lib“)#include“ser.h“//UserData*userdata[MaxUser];intuserdatap=-1;#defineBUFFER_SIZE2048voidCompressArrays(WSAEVENTevents[],SOCKETsockets[],DWORD*total,intindex){for(size_ti=index+1;i*total;i++){events[i-1]=events[i];}*total--;}intmain(intargc,char**argv){//InitData(userdata,MaxUser,userdatap);charresponse[BUFFER_LENGTH];WSADATAwsaData;charbuffer[BUFFER_SIZE];sockaddr_inInternetAddr;//客戶地址structsockaddr_incli;structsockaddr_incliArray[WSA_MAXIMUM_WAIT_EVENTS];intiLen;iLen=sizeof(cli);//udp發(fā)送SOCKETsSocket;structsockaddr_inser;charsend_buf[]=“udp!“;SOCKETsClient;SOCKETSocketArray[WSA_MAXIMUM_WAIT_EVENTS];WSANETWORKEVENTSNetworkEvents;WSAEVENTNewEvent;WSAEVENTEventArray[WSA_MAXIMUM_WAIT_EVENTS];SOCKETAccept,Listen;DWORDEventTotal=0;DWORDIndex;if(WSAStartup(MAKEWORD(2,2),wsaData)!=0){printf(“WSAStartup()\n“);return0;}//創(chuàng)建一個(gè)流式套接口Listen=socket(AF_INET,SOCK_STREAM,0);InternetAddr.sin_family=AF_INET;InternetAddr.sin_addr.s_addr=htonl(INADDR_ANY);InternetAddr.sin_port=htons(5050);if(bind(Listen,(PSOCKADDR)InternetAddr,sizeof(InternetAddr))==SOCKET_ERROR){printf(“bind()\n“);return0;}printf(“----------------------\n“);printf(“ServerWaiting\n“);printf(“----------------------\n“);//創(chuàng)建一個(gè)事件對(duì)象NewEvent=WSACreateEvent();//在Listen套接口上注冊(cè)套接口連接和關(guān)閉的網(wǎng)絡(luò)事件WSAEventSelect(Listen,NewEvent,FD_ACCEPT|FD_CLOSE);if(listen(Listen,5)==SOCKET_ERROR){printf(“l(fā)isten()\n“);return0;}SocketArray[EventTotal]=Listen;EventArray[EventTotal]=NewEvent;EventTotal++;//udpsSocket=socket(AF_INET,SOCK_DGRAM,0);if(sSocket==INVALID_SOCKET){printf(“failed“);return0;}ser.sin_family=AF_INET;ser.sin_port=htons(5051);//ser.sin_addr.s_addr=in9知識(shí)影響格局,格局決定命運(yùn)!et_addr(“127.0.0.1“);while(true){//在所有套接口上等待網(wǎng)絡(luò)事件的發(fā)生Index=WSAWaitForMultipleEvents(EventTotal,EventArray,FALSE,WSA_INFINITE,FALSE);if(WSAEnumNetworkEvents(SocketArray[Index-WSA_WAIT_EVENT_0],EventArray[Index-WSA_WAIT_EVENT_0],NetworkEvents)==SOCKET_ERROR){printf(“%d/n“,WSAGetLastError());printf(“WSAEnumNetworkEvents()\n“);return0;}//檢查FD_ACCEPTif(NetworkEvents.lNetworkEventsFD_ACCEPT){if(NetworkEvents.iErrorCode[FD_ACCEPT_BIT]!=0){WSACloseEvent(EventArray[Index-WSA_WAIT_EVENT_0]);printf(“FD_ACCEPTfailedwitherror%d\n“,NetworkEvents.iErrorCode[FD_ACCEPT_BIT]);break;}//接收新的連接,并將其存入套接口數(shù)組Accept=accept(SocketArray[Index-WSA_WAIT_EVENT_0],(structsockaddr*)cli,iLen);//當(dāng)套接口的數(shù)量超界時(shí),關(guān)閉該套接口if(EventTotalWSA_MAXIMUM_WAIT_EVENTS){printf(“Toomanyconnections“);closesocket(Accept);break;}NewEvent=WSACreateEvent();if(NewEvent==WSA_INVALID_EVENT){printf(“WSACreateEvent()\n“);break;}WSAEventSelect(Accept,NewEvent,FD_READ|FD_WRITE|FD_CLOSE);EventArray[EventTotal]=NewEvent;SocketArray[EventTotal]=Accept;cliArray[EventTotal]=cli;EventTotal++;printf(“Socket%dconnected\n“,Accept);}//一下處理FD_READ通知if(NetworkEvents.lNetworkEventsFD_READ){if(NetworkEvents.iErrorCode[FD_READ_BIT]!=0){WSACloseEvent(EventArray[Index-WSA_WAIT_EVENT_0]);printf(“FD_READfailedwitherror%d\n“,NetworkEvents.iErrorCode[FD_READ_BIT]);break;}//從套接口讀入數(shù)據(jù)intiRecv=recv(SocketArray[Index-WSA_WAIT_EVENT_0],buffer,sizeof(buffer),0);if(iRecv==0){break;}elseif(iRecv==SOCKET_ERROR){printf(“recv()\n“);break;}else{//請(qǐng)求端10知識(shí)影響格局,格局決定命運(yùn)!IPser.sin_addr.s_addr=inet_addr(inet_ntoa(cliArray[Index-WSA_WAIT_EVENT_0].sin_addr));printf(“AcceptedclientIP:[%s],port:[%d]\n“,inet_ntoa(cliArray[Index-WSA_WAIT_EVENT_0].sin_addr),ntohs(cliArray[Index-WSA_WAIT_EVENT_0].sin_port));printf(“recv:%s\n“,buffer);memset(response,'\0',sizeof(response));deal(buffer,userdata,userdatap,response,inet_ntoa(cliArray[Index-WSA_WAIT_EVENT_0].sin_addr));printf(“response:%s\n“,response);inti;if(response[0]=='2'response[1]=='0'){//處理20群聊printf(“recv:%s\n“,buffer);for(i=0;i=userdatap;i++){if(userdata[i]-Log==0)continue;ser.sin_addr.s_addr=inet_addr(userdata[i]-MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}}elseif(response[0]=='5'response[1]=='0'){//處理50單聊charstrwchy[2048];strcpy(strwchy,response);printf(“recv:%s\n“,buffer);for(i=1;istrlen(strwchy);i++)if(strwchy[i]==':')break;strwchy[i]='\0';printf(“strwchy:%s\n“,strwchy+2);for(i=0;i=userdatap;i++){if(strcmp((buffer+1),(strwchy+2))==0){if(strcmp((strwchy+2),userdata[i]-UserName)==0){//發(fā)送給單聊對(duì)象ser.sin_addr.s_addr=inet_addr(userdata[i]-MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}}else{if(strcmp((buffer+1),userdata[i]-UserName)==0){//發(fā)送給單聊對(duì)象ser.sin_addr.s_addr=inet_addr(userdata[i]-MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}if(strcmp((strwchy+2),userdata[i]-UserName)==0){//發(fā)送給單聊對(duì)象ser.sin_addr.s_addr=inet_addr(userdata[i]-MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}}}}elseif(response[0]=='4'response[1]=='0'){//處理40在線人數(shù)printf(“recv:%s\11知識(shí)影響格局,格局決定命運(yùn)!n“,buffer);for(i=0;i=userdatap;i++){if(strcmp((buffer+1),userdata[i]-UserName)==0){//發(fā)到請(qǐng)求方的接收端ser.sin_addr.s_addr=inet_addr(userdata[i]-MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}}}else{MySendMessage(sSocket,response,sizeof(response),(SOCKADDR*)ser,sizeof(ser));}}}//以下處理FD_CLOSE通知if(NetworkEvents.lNetworkEventsFD_CLOSE){if(NetworkEvents.iErrorCode[FD_WRITE_BIT]!=0){WSACloseEvent(EventArray[Index-WSA_WAIT_EVENT_0]);printf(“FD_WRITEfaieldwitherror%d\n“,NetworkEvents.iErrorCode[FD_WRITE_BIT]);break;}//關(guān)閉套接口closesocket(SocketArray[Index-WSA_WAIT_EVENT_0]);//從套接口事件和事件數(shù)組中刪除關(guān)閉的套接口的有關(guān)信息CompressArrays(EventArray,SocketArray,EventTotal,Index-WSA_WAIT_EVENT_0);}}WSACleanup();return0;}第3章服務(wù)器設(shè)計(jì)3.1流程圖3.2代碼#includeWinSock2.h#includestdio.h#includestdlib.h#includestring.h#pragmacomment(lib,“ws2_32.lib“)#defineDEFAULT_PORT5051//FORRECV#defineBUFFER_LENGTH1000voidMySendMessage(SOCKETsSocket,char*response,intresponseLen,structsockaddr*cli,intcliLen);voidmain(){intiPort=DEFAULT_PORT;WSADATAwsaData;SOCKETsSocket,wchysSocket;intiLen,wchyiLen;intiSend;intiRecv;charsend_buf[1000];charname[255];charrecv_buf[BUFFER_LENGTH];char*ip;PHOSTENThostinfo;structsockaddr_inser,cli,wchy;if(WSAStartup(MAKEWORD(2,2),wsaData)!=0){printf(“FailedtoloadWinsock.\n“);return;}if(gethostname(name,sizeof(name))==0){if((hostinfo=gethostbyname(name))!=NULL){ip=inet_ntoa(*(structin_addr*)*hostinfo-h_addr_list);}}printf(“----------------------\n“);printf(“cServerWaiting\n“);printf(“ip%s\n“,ip);printf(“----------------------\n“);sSocket=socket(AF_INET,SOCK_DGRAM,0);if(sSocket==INVALID_SOC12知識(shí)影響格局,格局決定命運(yùn)!KET){printf(“socket()Faild:%d\n“,WSAGetLastError());return;}ser.sin_family=AF_INET;ser.sin_port=htons(iPort);ser.sin_addr.s_addr=htonl(INADDR_ANY);if(bind(sSocket,(LPSOCKADDR)ser,sizeof(ser))==SOCKET_ERROR){printf(“bind()Faild:%d\n“,WSAGetLastError());return;}iLen=sizeof(cli);memset(recv_buf,0,sizeof(recv_buf));while(1){//接收數(shù)據(jù)包確定cli表示cli存有客戶端發(fā)來(lái)的ip和portiRecv=recvfrom(sSocket,recv_buf,BUFFER_LENGTH,0,(SOCKADDR*)cli,iLen);if(iRecv==SOCKET_ERROR){printf(“recvfrom()Faild:%d\n“,WSAGetLastError());return;}elseif(iRecv==0)break;else{//接收到了正確數(shù)據(jù)//printf(“[+]%s\n“,recv_buf);//控制信息的種類有000110111220213031//00注冊(cè)成功01注冊(cè)失敗10登陸成功11.12表示登陸失敗20表示一次成功會(huì)話21表示錯(cuò)誤會(huì)話30表示成功推出31表示錯(cuò)誤推出冊(cè)成功\n“);elseprintf(“注冊(cè)失?。躰“);break;case'1':if(recv_buf[1]=='0'){printf(“登陸成功\n“);wchy.sin_family=AF_INET;wchy.sin_port=htons(5053);wchy.sin_addr.s_addr=inet_addr(“127.0.0.1“);wchysSocket=socket(AF_INET,SOCK_DGRAM,0);if(wchysSocket==INVALID_SOCKET){printf(“socket()Failed:%d\n“,WSAGetLastError());return;}wchyiLen=sizeof(wchy);strcpy(send_buf,“##“);MySendMessage(wchysSocket,send_buf,sizeof(send_buf),(structsockaddr*)wchy,wchyiLen);}elseif(recv_buf[1]=='@'){printf(“已經(jīng)在其他地方登陸\n“);wchy.sin_family=AF_INET;wchy.sin_port=htons(5053);wchy.sin_addr.s_addr=inet_addr(“127.0.0.1“);wchysSocket=socket(AF_INET,SOCK_DGRAM,0);if(wchysSocket==INVALID_SOCKET){printf(“socket()Failed:%d\13知識(shí)影響格局,格局決定命運(yùn)!n“,WSAGetLastError());return;}wchyiLen=sizeof(wchy);strcpy(send_buf,“**“);MySendMessage(wchysSocket,send_buf,sizeof(send_buf),(structsockaddr*)wchy,wchyiLen);}else{printf(“登陸失?。躰“);wchy.sin_family=AF_INET;wchy.sin_port=htons(5053);wchy.sin_addr.s_addr=inet_addr(“127.0.0.1“);wchysSocket=sock
溫馨提示
- 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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年違約借款合同違約責(zé)任追究辦法3篇
- 2025年度個(gè)人房屋買賣價(jià)格調(diào)整及支付合同4篇
- 2025年度企業(yè)應(yīng)收賬款債權(quán)轉(zhuǎn)讓與風(fēng)險(xiǎn)控制協(xié)議書(shū)3篇
- 2025年度房地產(chǎn)樣板間設(shè)計(jì)與施工合同范本4篇
- 2025年度電子商務(wù)個(gè)人勞務(wù)派遣合作協(xié)議書(shū)4篇
- 工廠租地合同(2篇)
- 二零二五年度民政局離婚協(xié)議書(shū)模板法律咨詢附加服務(wù)合同4篇
- 2025年度銷售顧問(wèn)市場(chǎng)調(diào)研聘用合同2篇
- 2024西部縣域經(jīng)濟(jì)百?gòu)?qiáng)研究
- STEM教育實(shí)踐講解模板
- 2025年山東浪潮集團(tuán)限公司招聘25人高頻重點(diǎn)提升(共500題)附帶答案詳解
- 2024年財(cái)政部會(huì)計(jì)法律法規(guī)答題活動(dòng)題目及答案一
- 2025年江西省港口集團(tuán)招聘筆試參考題庫(kù)含答案解析
- (2024年)中國(guó)傳統(tǒng)文化介紹課件
- 液化氣安全檢查及整改方案
- 《冠心病》課件(完整版)
- 2024年云網(wǎng)安全應(yīng)知應(yīng)會(huì)考試題庫(kù)
- 公園保潔服務(wù)投標(biāo)方案
- 光伏電站項(xiàng)目合作開(kāi)發(fā)合同協(xié)議書(shū)三方版
- 高中物理答題卡模板
- 芳香植物與芳香療法講解課件
評(píng)論
0/150
提交評(píng)論