windows的一个socket 客户端程序
windows的一个socket 客户端程序
#include <iostream> #include <WinSock2.h> #include <WS2tcpip.h> #include <chrono> #include <thread> // 链接库 #pragma comment(lib, "Ws2_32.lib") int main() { // 初始化 Winsock WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { std::cerr << "Failed to initialize Winsock\n"; return 1; } // 创建套接字 SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (client_socket == INVALID_SOCKET) { std::cerr << "Failed to create socket\n"; WSACleanup(); return 1; } // 设置服务器地址 sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(9000); inet_pton(AF_INET, "192.168.21.49", &server_addr.sin_addr); // 连接到服务器 if (connect(client_socket, reinterpret_cast<SOCKADDR*>(&server_addr), sizeof(server_addr)) == SOCKET_ERROR) { std::cerr << "Failed to connect to server\n"; closesocket(client_socket); WSACleanup(); return 1; } // 每隔1秒发送一次消息 while (true) { //const char* message = "hello world"; //if (send(client_socket, message, strlen(message), 0) == SOCKET_ERROR) { // std::cerr << "Failed to send message\n"; // closesocket(client_socket); // WSACleanup(); // return 1; //} //std::cout << "Message sent: " << message << std::endl; //std::this_thread::sleep_for(std::chrono::seconds(3)); // 等待 N 秒 // 每隔 n 秒发送一次数据 std::string binaryData = "\x5F\x0F"; // 二进制数据流 "0101 1111 0000 1111" // 发送数据 int bytesSent = send(client_socket, binaryData.c_str(), binaryData.length(), 0); if (bytesSent == SOCKET_ERROR) { std::cerr << "Failed to send data: " << WSAGetLastError() << std::endl; closesocket(client_socket); WSACleanup(); return 1; } std::cout << "Sent " << bytesSent << " bytes of data." << std::endl; // 等待1秒 std::this_thread::sleep_for(std::chrono::seconds(1)); } // 关闭套接字 closesocket(client_socket); WSACleanup(); return 0; }