TCP服务器:
// TCP服务器.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <WinSock2.h> #include <windows.h> #pragma comment(lib, "WS2_32.lib") int _tmain(int argc, _TCHAR* argv[]) { WSADATA data; WORD w = MAKEWORD(2, 0); //定义版本号码 char sztext[] = "welcome yuippe\r\n"; ::WSAStartup(w, &data); //初始化套接字库 SOCKET s, s1; //定义连接套接字和数据收发套接字句柄 s = ::socket(AF_INET, SOCK_STREAM, 0); //创建TCP套接字 sockaddr_in addr, addr2; //定义套接字地址结构 int n = sizeof(addr2); //获取套接字地址结构大小 addr.sin_family = AF_INET; //初始化地址结构 addr.sin_port = htons(75); addr.sin_addr.S_un.S_addr = INADDR_ANY; ::bind(s, (sockaddr*)&addr, sizeof(addr)); ::listen(s, 5); printf("服务器已经启动\r\n"); while (true) { s1 = ::accept(s, (sockaddr*)&addr2, &n); if( s1!= NULL ) { printf("%s已经连接上\r\n", inet_ntoa(addr2.sin_addr)); ::send(s1, sztext, sizeof(sztext), 0); //向客户端发送字符数组 } ::closesocket(s); ::closesocket(s1); ::WSACleanup(); //释放套接字库 if (getchar()) { return 0; } else { ::Sleep(100); } } return 0; }
// TCP客户端.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <WinSock2.h> #pragma comment(lib, "WS2_32.lib") int _tmain(int argc, _TCHAR* argv[]) { WSADATA data; WORD w = MAKEWORD(2, 0); ::WSAStartup(w, &data); SOCKET s; char sztext[100] = {0}; s = ::socket(AF_INET, SOCK_STREAM, 0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(75); addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); printf("客户端已经启动\r\n"); ::connect(s, (sockaddr*)&addr, sizeof(addr)); ::recv(s, sztext, sizeof(sztext), 0); printf("%s\r\n", sztext); ::closesocket(s); ::WSACleanup(); if (getchar()) { return 0; } else { ::Sleep(100); } return 0; }