server 端 // Server.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Winsock2.h> #pragma comment(lib,"ws2_32.lib") #define PORT_NUMBER 11234 #define MAX_BUF_SIZE 1024 int _tmain(int argc, _TCHAR* argv[]) { WSADATA wSaData; WORD dwSockVersion = MAKEWORD(2,2); if (0 != WSAStartup(dwSockVersion,&wSaData)) //协商版本号 { printf("Arrange Version Failure"); return -1; } SOCKET nSocket; nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //创建TCP socket if (INVALID_SOCKET == nSocket) { printf("invalid socket"); WSACleanup(); return -1; } sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_addr.s_addr = inet_addr("127.0.0.1"); sa.sin_port = htons(PORT_NUMBER);//选择一个端口号 if (bind(nSocket,(sockaddr *)&sa,sizeof(sa)) < 0) //绑定 { closesocket(nSocket); return -1; } listen(nSocket,2); sockaddr_in addr_client; int nAddrLen = sizeof(addr_client); while(TRUE) { //SOCKET nSock = accept(nSocket,(sockaddr *)&addr_client,&nAddrLen); SOCKET nSock = accept(nSocket,NULL,NULL); if (INVALID_SOCKET == nSock) { printf("failure to accept"); continue; } char tmp[MAX_BUF_SIZE] = {0}; char buf[MAX_BUF_SIZE] = {0}; strcpy(tmp,"this is server"); send(nSock, tmp, (int)strlen(tmp), 0); int nRecv = recv(nSock, buf, MAX_BUF_SIZE, 0); if (nRecv > 0) { printf("%s/n",buf); } closesocket(nSock); return 0; } } Client 端 // Client.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Winsock2.h> #pragma comment(lib,"ws2_32.lib") #define MAX_BUF_SIZE 1024 #define PORT_NUMBER 11234 int _tmain(int argc, _TCHAR* argv[]) { WSADATA wSaData; WORD dwSockVersion = MAKEWORD(2,2); if (0 != WSAStartup(dwSockVersion,&wSaData)) //协商版本号 { printf("Arrange Version Failure"); return -1; } SOCKET nSocket; nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //创建TCP socket if (INVALID_SOCKET == nSocket) { printf("invalid socket"); WSACleanup(); return -1; } sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_addr.s_addr = inet_addr("127.0.0.1"); sa.sin_port = htons(PORT_NUMBER); if ( 0 != connect( nSocket,( const SOCKADDR * )&sa, sizeof(sa) ) ) return -1; char buf[MAX_BUF_SIZE] = {0}; char tmp[MAX_BUF_SIZE] = {0}; strcpy(tmp,"this is Client!"); int nRecv = 0; nRecv = recv(nSocket, buf, MAX_BUF_SIZE, 0); if (nRecv > 0) { printf("%s/n",buf); send(nSocket, tmp, (int)strlen(tmp), 0); } closesocket(nSocket); WSACleanup(); return 0; } 在VS 2005下编译通过。也作为自己学习之用 2010-08-11 16:40:28