zoukankan      html  css  js  c++  java
  • Socket-window通讯

    #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 1x003");
    		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;
    
    }
    

      

  • 相关阅读:
    MDI窗体容器
    记事本制作、流的初步引用、窗口的三种显示类型
    ListVies控件的应用
    变量常量
    百度地图自定义离线地图
    通过配置文件方式修改 axios 请求地址
    百度地图坐标偏差
    Vue 全局指令限制输入框输入
    axios post请求发送数组
    WebSocket
  • 原文地址:https://www.cnblogs.com/alexYuin/p/9267685.html
Copyright © 2011-2022 走看看