winsock 简单的通信

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winsock 简单的通信相关的知识,希望对你有一定的参考价值。

头文件

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


说明

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


以上是关于winsock 简单的通信的主要内容,如果未能解决你的问题,请参考以下文章

VB如何使用Winsock进行1对多通信

Server->Client 之间的 C++ Winsock 通信,反之亦然

实验一:基于Winsock完成简单的网络程序开发

Winsock - 停止接受新连接但与现有连接保持通信

winsock 客户端和服务器通信

力控组态添加winsock