您好,欢迎访问三七文档
TCPECHO服务器端//server.cpp:定义控制台应用程序的入口点。#includestdafx.h#pragmacomment(lib,ws2_32.lib)#includestdio.h#includeWinsock2.h#includestring.h#includememory.hint_tmain(intargc,_TCHAR*argv[]){WSADatawsaData;interr=WSAStartup(WINSOCK_VERSION,&wsaData);if(0!=err){return-1;}SOCKETsock=socket(AF_INET,SOCK_STREAM,0);if(INVALID_SOCKET==sock){printf(socket()Failed:%d\n,WSAGetLastError());WSACleanup();return-1;}sockaddr_inLocaAddr;LocaAddr.sin_family=AF_INET;LocaAddr.sin_port=htons(10000);LocaAddr.sin_addr.s_addr=htonl(INADDR_ANY);err=bind(sock,(sockaddr*)&LocaAddr,sizeof(LocaAddr));if(SOCKET_ERROR==err){printf(bind()Failed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}err=listen(sock,5);if(SOCKET_ERROR==err){printf(listen()Failed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}sockaddr_inClientAddr;intAddrLen=sizeof(ClientAddr);SOCKETsockConnected=accept(sock,(sockaddr*)&ClientAddr,&AddrLen);if(INVALID_SOCKET==sockConnected){printf(accpet()Failed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}charrbuf[1024];while(1){memset(rbuf,0,1024);intrByte=recv(sockConnected,rbuf,1024,0);if(SOCKET_ERROR==rByte)/*出错处理*/{printf(recvFailed:%d\n,WSAGetLastError());closesocket(sockConnected);break;}if(0==rByte){printf(Connectionisclosed.\n);shutdown(sockConnected,SD_SEND);closesocket(sockConnected);break;}printf(TCPrecv[%d]DATA:%s\n,rByte,rbuf);intsByte=send(sockConnected,rbuf,rByte,0);if(INVALID_SOCKET==sByte){printf(send()Failed:%d\n,WSAGetLastError());closesocket(sockConnected);break;}}closesocket(sock);WSACleanup();return0;}客户端//SOCKET.cpp:定义控制台应用程序的入口点。#includestdafx.h#pragmacomment(lib,ws2_32.lib)#includestdio.h#includeWinsock2.h#includestring.h#includememory.hint_tmain(intargc,_TCHAR*argv[]){WSADatawsaData;interr=WSAStartup(WINSOCK_VERSION,&wsaData);if(0!=err){return-1;}SOCKETsock;sock=socket(AF_INET,SOCK_STREAM,0);if(INVALID_SOCKET==sock)//出错处理{printf(socket()Failed:%d\n,WSAGetLastError());WSACleanup();return-1;}sockaddr_inServerAddr;ServerAddr.sin_family=AF_INET;ServerAddr.sin_port=htons(10000);ServerAddr.sin_addr.s_addr=inet_addr(127.0.0.1);err=connect(sock,(sockaddr*)&ServerAddr,sizeof(ServerAddr));if(SOCKET_ERROR==err){printf(connect()Failed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}chardata[]=HelloWorld!;intsByte=send(sock,data,strlen(data),0);if(SOCKET_ERROR==sByte){printf(send()Failed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}printf(TCPsend[%d]DATA:%s\n,sByte,data);charrbuf[1024];while(1){memset(rbuf,0,1024);intrByte=recv(sock,rbuf,1024,0);if(SOCKET_ERROR==rByte){printf(recvFailed:%d\n,WSAGetLastError());closesocket(sock);WSACleanup();return-1;}if(0==rByte)//对方关闭了连接{printf(Connectionisclosed.\n);break;}printf(TCPrecv[%d]DATA:%s\n,rByte,rbuf);}closesocket(sock);WSACleanup();return0;}
本文标题:TCP协议代码
链接地址:https://www.777doc.com/doc-8506888 .html