Socket-window通讯
阅读原文时间:2023年07月15日阅读:1

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include
#include
#include
#include

#include
#include

using namespace std;
#pragma comment(lib, "ws2_32.lib")

int main()
{
WORD sockVersion = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(sockVersion, &data) != 0)
{
return 0;
}

int i = 0;  
while (true)  
{  
    std::cout << ++i << std::endl;

    SOCKET sclient = socket(AF\_INET, SOCK\_STREAM, IPPROTO\_TCP);  
    if (sclient == INVALID\_SOCKET)  
    {  
        printf("invalid socket!");  
        return 0;  
    }

    sockaddr\_in serAddr;  
    serAddr.sin\_family = AF\_INET;  
    serAddr.sin\_port = htons(2115);  
    serAddr.sin\_addr.S\_un.S\_addr = inet\_addr("192.168.1.100");  
    if (connect(sclient, (sockaddr \*)&serAddr, sizeof(serAddr)) == SOCKET\_ERROR)  
    {  //连接失败  
        printf("connect error !");  
        closesocket(sclient);  
        return 0;  
    }

    // 和设备通讯时,要注意起止字符  
    // \\x2是ASKII的通用转义格式  
    std::string sdata("\\x002set parameter 1\\x003");  
    const char \* sendData;  
    sendData = sdata.c\_str();  
    int sta = send(sclient, sendData, strlen(sendData), 0);  
    if (sta == -1)  
    {  
        std::cout << "send failed !" << std::endl;  
    }

    char recData\[255\];  
    int ret = recv(sclient, recData, 255, 0);  
    if (ret>0) {  
        recData\[ret\] = 0x00;  
        std::string result(recData);

    }  
    closesocket(sclient);  
}

WSACleanup();  
return 0;

}