C++封装TCP windows平台
时间: 2024-01-17 11:04:16 浏览: 84
以下是一个简单的C++封装TCP的示例代码,适用于Windows平台:
```cpp
#include <iostream>
#include <string>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
class TcpClient {
private:
SOCKET clientSocket;
sockaddr_in serverAddr;
public:
TcpClient() {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(1500);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
}
~TcpClient() {
closesocket(clientSocket);
WSACleanup();
}
bool Connect() {
if (connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cout << "Failed to connect to server." << std::endl;
return false;
}
return true;
}
bool Send(const std::string& data) {
if (send(clientSocket, data.c_str(), data.size(), 0) == SOCKET_ERROR) {
std::cout << "Failed to send data." << std::endl;
return false;
}
return true;
}
std::string Receive() {
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(clientSocket, buffer, sizeof(buffer), 0) == SOCKET_ERROR) {
std::cout << "Failed to receive data." << std::endl;
return "";
}
return std::string(buffer);
}
};
int main() {
TcpClient client;
if (client.Connect()) {
std::cout << "客户端启动" << std::endl;
std::cout << "sever:" << client.Receive() << std::endl;
}
getchar();
return 0;
}
```
阅读全文