189 8069 5689

winsock简单的通信-创新互联

头文件

创新互联公司-专业网站定制、快速模板网站建设、高性价比建邺网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式建邺网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖建邺地区。费用合理售后完善,十年实体公司更值得信赖。

#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);

说明

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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文名称:winsock简单的通信-创新互联
标题URL:http://cdxtjz.cn/article/pedie.html

其他资讯