资源描述:
《Socket服务器和客户端C.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、客户端:#includeusingnamespacestd;#defineSERVPORT7861/*服务器监听端口号*/#defineDEST_IP"192.168.1.35"#defineMAXDATASIZE100;int_tmain(intargc,_TCHAR*argv[]){intsockfd,recvbytes;charbuf[MAXDATASIZE];structhostent*host;structsockaddr_inserv_addr;structsockaddr_indest_addr;/*目的地址*/WORDwVersionRequested
2、;WSADATAwsaData;interr;wVersionRequested=MAKEWORD(2,0);err=WSAStartup(wVersionRequested,&wsaData);if(0!=err){cout<<"Socketfailed";return0;}if(LOBYTE(wsaData.wVersion)!=2
3、
4、HIBYTE(wsaData.wVersion)!=0){WSACleanup();return0;}if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){perror("socket创建出错!");exit(1
5、);}serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(SERVPORT);/*serv_addr.sin_addr=*((structin_addr*)host->h_addr);*/serv_addr.sin_addr.s_addr=inet_addr(DEST_IP);memset(&(serv_addr.sin_zero),0,8);if(connect(sockfd,(structsockaddr*)&serv_addr,sizeof(structsockaddr))==-1){perror("connect出错!")
6、;//exit(1);}charszMsg[]="hao";intnlen=sizeof(serv_addr);intuIndex=0;while(1){Sleep(1000);if(send(sockfd,"Hello,areconnected!",23,0)==-1){cout<