#include <iostream> #include <vector> #include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
typedef struct { char HostName[32]; char Buffer[32]; }message;
message msg;
int main(int argc, char* argv[]) { WSADATA WSAData; SOCKET sock;
WSAStartup(MAKEWORD(2, 0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == INVALID_SOCKET) { std::cout << "创建套接字失败" << std::endl; }
struct sockaddr_in ClientAddr; ClientAddr.sin_family = AF_INET; ClientAddr.sin_port = htons(9999); ClientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
auto res = connect(sock, (LPSOCKADDR)&ClientAddr, sizeof(ClientAddr));
if (res == SOCKET_ERROR) { std::cout << "链接失败." << std::endl; }
std::vector<message> vect;
for (int x = 0; x < 10; x++) { message ptr; sprintf(ptr.HostName, "lyshark %d", x); sprintf(ptr.Buffer, "hello lyshark %d", x); vect.push_back(ptr); }
char count[32] = { 0 };
sprintf(count, "%d", vect.size());
int send_count_flag = send(sock, count, sizeof(count), 0);
if (send_count_flag != 0) { std::cout << "发送循环次数: " << count << std::endl;
for (int x = 0; x < vect.size(); x++) { char send_buf[4096] = { 0 };
memcpy(send_buf, &vect[x], sizeof(message)); int send_flag = send(sock, send_buf, sizeof(send_buf), 0); if (send_flag != 0) { char recv_buf[32] = { 0 }; recv(sock, recv_buf, sizeof(recv_buf), 0); std::cout << "发送完成,接收状态码: " << recv_buf << std::endl; } } }
closesocket(sock); WSACleanup(); return 0; }
|