}
break; } recvBuf[iLen] = '\0'; cout<<recvBuf<<endl; closesocket(sockConn); //关闭套接字 }
closesocket(sockSrv);//关闭服务器监听套接字 WSACleanup(); return 0;
客户端:
#include <winsock2.h> #include <iostream> using namespace std; #include <string.h>
int main(int argc, char *argv[]) { const int DEFAULT_PORT = 5000; WORD wVersionRequested; WSADATA wsaData; int err,iLen; if (argc < 2) { cout<<"Command:TcpEx_Client ServerIP"<<endl; return 0; } wVersionRequested=MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { cout<<"加载WinSock失败!"; return 0; } //创建用于连接的套接字 SOCKET sockClient = socket(AF_INET,SOCK_STREAM,0); if (sockClient == INVALID_SOCKET) { cout<<"socket() fail:"<<WSAGetLastError()<<endl; return 0; } SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; addrSrv.sin_addr.S_un.S_addr = inet_addr(argv[1]); addrSrv.sin_port = htons(DEFAULT_PORT);