winsock簡單的通信-創(chuàng)新互聯(lián)

頭文件

創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設、高性價比建鄴網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式建鄴網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設找我們,業(yè)務覆蓋建鄴地區(qū)。費用合理售后完善,十年實體公司更值得信賴。

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

}

// 創(chuàng)建 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);

說明

    當前內嵌代碼進行自動化測試

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

分享文章:winsock簡單的通信-創(chuàng)新互聯(lián)
分享地址:http://muchs.cn/article4/pedie.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App設計、靜態(tài)網(wǎng)站外貿建站移動網(wǎng)站建設、Google品牌網(wǎng)站設計

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司