头文件
创新互联公司-专业网站定制、快速模板网站建设、高性价比建邺网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式建邺网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖建邺地区。费用合理售后完善,十年实体公司更值得信赖。#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);
说明
当前内嵌代码进行自动化测试
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享文章:winsock简单的通信-创新互联
分享地址:https://www.cdcxhl.com/article4/pedie.html
成都网站建设公司_创新互联,为您提供App设计、静态网站、外贸建站、移动网站建设、Google、品牌网站设计
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联