#include <stdio.h> #include <winsock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData) != 0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; CInitSock initSock; // 初始化Winsock库 int main1(); int main2(); void main() { printf("Please select a item:/n"); printf("s:Server/n"); printf("c:Client/n"); char a; while(1){ scanf("%c",&a); if(a=='s'){main1();break;} else if(a=='c'){main2();break;} else continue; } } ///服务器端绑定监听时,每接收一个新链接时,都会接收客户端来的数据;向客户端发送数据 ///客户端连接上服务器后,就向服务器端发送数据;接收一次从服务器发来的数据 //Server int main1() { // 创建套节字 SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sListen == INVALID_SOCKET) { printf("Failed socket() /n"); return 0; } // 填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(4567); sin.sin_addr.S_un.S_addr = INADDR_ANY; // 绑定这个套节字到一个本地地址 if(::bind(sListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind() /n"); return 0; } // 进入监听模式 if(::listen(sListen, 2) == SOCKET_ERROR) { printf("Failed listen() /n"); return 0; } // 循环接受客户的连接请求 sockaddr_in remoteAddr; int nAddrLen = sizeof(remoteAddr); SOCKET sClient; while(TRUE) { // 接受一个新连接 sClient = ::accept(sListen, (SOCKADDR*)&remoteAddr, &nAddrLen); if(sClient == INVALID_SOCKET) { printf("Failed accept()"); continue; } printf(" 接受到一个连接:%s /r/n", inet_ntoa(remoteAddr.sin_addr)); // 接收客户端来的数据 char buff[256]; int nRecv = ::recv(sClient, buff, 256, 0); if(nRecv > 0) { buff[nRecv] = '/0'; printf(" 接收到数据:%s", buff); } //发送数据 char szText[] = "data from TCP Server to TCP Client success! /r/n"; // 向客户端端发送数据 ::send(sClient, szText, strlen(szText), 0); // 关闭同客户端的连接 ::closesocket(sClient); } // 关闭监听套节字 ::closesocket(sListen); return 0; } //Client int main2() { // 创建套节字 SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(s == INVALID_SOCKET) { printf(" Failed socket() /n"); return 0; } // 也可以在这里调用bind函数绑定一个本地地址 // 否则系统将会自动安排 // 填写远程地址信息 sockaddr_in servAddr; servAddr.sin_family = AF_INET; servAddr.sin_port = htons(4567); // 注意,这里要填写服务器程序(TCPServer程序)所在机器的IP地址 // 如果你的计算机没有联网,直接使用127.0.0.1即可 servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); if(::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1) { printf(" Failed connect() /n"); return 0; } char szText[] = "data from TCP Client to TCP Server success! /r/n"; // 向服务器端发送数据 ::send(s, szText, strlen(szText), 0); // 接收服务器来的数据 char buff[256]; int nRecv = ::recv(s, buff, 256, 0); if(nRecv > 0) { buff[nRecv] = '/0'; printf(" 接收到数据:%s", buff); } // 关闭套节字 ::closesocket(s); return 0; }