winsock 简单的通信
  TEZNKK3IfmPf 2023年11月14日 23 0

头文件

#include <WinSock2.h>

#include <string>

#include <WS2tcpip.h>

#include <IPHlpApi.h>

#include <stdio.h>

#pragma comment(lib, "WS2_32.lib")

 

源代码

// 初始化 Winsock

WSADATA wsaData;

int iResult;

iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (iResult != 0) {

printf("WSAStartup failed: %d\n", iResult);

return NULL;

}

 

// 获取连接属性

struct addrinfo * result = NULL, *ptr = NULL, hints;

ZeroMemory(&hints, sizeof(hints));

hints.ai_family = AF_INET;

hints.ai_socktype = SOCK_STREAM;

hints.ai_protocol = IPPROTO_TCP;

 

iResult = getaddrinfo("192.168.0.18", "7002", &hints, &result);

//iResult = getaddrinfo("192.168.37.187", "7002", &hints, &result);

if (iResult != 0) {

printf("getaddrinfo failed: %d\n", iResult);

WSACleanup();

return NULL;

}

 

// 创建 Socket 对象

ptr = result;

SOCKET ConnectSocket = INVALID_SOCKET;

ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

if (ConnectSocket == INVALID_SOCKET) {

printf("Error at socket(): %ld\n", WSAGetLastError());

freeaddrinfo(result);

WSACleanup();

return NULL;

}

 

// 链接

iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

if (iResult == SOCKET_ERROR) {

printf("Error at socket(): %ld\n", WSAGetLastError());

closesocket(ConnectSocket);

ConnectSocket = INVALID_SOCKET;

}

 

int nSendBuf = 32 * 1000;//设置为32K

setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nSendBuf, sizeof(int));

// Should really try the next address returned by getaddrinfo

// if the connect call failed

// But for this simple example we just free the resources

// returned by getaddrinfo and print an arror message

//freeaddrinfo(result);

 

if (ConnectSocket == INVALID_SOCKET) {

printf("Unable to connect to server!\n");

WSACleanup();

return NULL;

}

 

send(ConnectSocket, strSendContext.c_str(), strSendContext.length(), 0);

 

char szbuffer[1024] = { 0 };

recv(ConnectSocket, szbuffer, 1024, 0);

::closesocket(ConnectSocket);

 

说明

    当前内嵌代码进行自动化测试

 

编译错误

1)错误 LNK2019 无法解析的外部符号 __imp__WSACloseEvent@4

解决:在cpp文件Include后添加 #pragma comment(lib,"ws2_32.lib")

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

TEZNKK3IfmPf