头文件
公司主营业务:成都网站建设、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出渭城免费做网站回馈大家。
#include
#include
#include
#include
#include
#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);
说明
当前内嵌代码进行自动化测试