TCP一个简单应用
#include "stdafx.h" #include<WinSock2.h> #include<windows.h> #include<iostream> using namespace std; #pragma comment (lib,"ws2_32.lib") //Client int main() { WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { cout << "网络环境初始化失败" << endl; return -1; } SOCKET sSever = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sSever==INVALID_SOCKET) { cout << "套接字创建失败" << endl; closesocket(sSever); WSACleanup(); return -1; } SOCKADDR_IN si; si.sin_family = AF_INET; si.sin_port = htons(80); si.sin_addr.S_un.S_addr = inet_addr("14.215.177.38"); int ret = connect(sSever, (sockaddr *)&si, sizeof(sockaddr)); if (ret==SOCKET_ERROR) { cout << "网络连接失败" << endl; closesocket(sSever); WSACleanup(); return -1; } char *request = "GET /index.html HTTP/1.1\r\n" "User-Agent:Mozilla/4.0\r\n" "Host:www.baidu.com\r\n\r\n"; ret = send(sSever, request, strlen(request), 0); if (ret == SOCKET_ERROR) { cout << "发送失败" << endl; closesocket(sSever); WSACleanup(); return -1; } int recvLen = 1; char *szBuf=new char[10240000]; memset(szBuf, 0, sizeof(szBuf)); while (recvLen>0) { recvLen = recv(sSever, szBuf, 10240000, 0); if (recvLen>0) { szBuf[recvLen] = 0; } else { szBuf[0] = 0; } printf("revc html resource from Sever:%s", szBuf); } delete[]szBuf; return 0; }