码迷,mamicode.com
首页 > Windows程序 > 详细

Socket-window通讯

时间:2018-07-05 12:51:08      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:rtu   erro   ted   send   转义   设备   std   tcp   comm   

#define _WINSOCK_DEPRECATED_NO_WARNINGS


#include<WINSOCK2.H>
#include<STDIO.H>
#include<iostream>
#include<string>

#include <thread>
#include <mutex>

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;

}

  

Socket-window通讯

标签:rtu   erro   ted   send   转义   设备   std   tcp   comm   

原文地址:https://www.cnblogs.com/alexYuin/p/9267685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!