c/c++语言开发共享关于Arduino上TCP的问题

我正在试验我的Arduino Leonardo和一个简单的C套接字服务器。 C部分必须向Arduino发送一个字符串,但我无法连接到arduino(套接字初始化后C函数被阻塞,无法连接到Arduino)。 C函数代码是:

#include  #include  #pragma comment(lib, "ws2_32.lib") //Winsock Library int connect() { WSADATA wsa; SOCKET s; struct sockaddr_in server; char* message; printf("nInitialising Winsock..."); if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { printf("Failed. Error Code : %d", WSAGetLastError()); return 1; } printf("Initialised.n"); //Create a socket if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { printf("Could not create socket : %d", WSAGetLastError()); } else printf("Socket created.n"); server.sin_addr.s_addr = inet_addr("192.168.1.144"); server.sin_family = AF_INET; server.sin_port = htons(9600); //Connect to remote server //HERE I RECEIVE THE ERROR: <--------------------------- if (connect(s, (struct sockaddr*)&server, sizeof(server)) < 0) { puts("connect error"); return 1; } puts("Connected"); //Send some data message = "This is a Testn"; if (send(s, message, strlen(message), 0) < 0) { puts("Send failed"); return 1; } puts("Data Sendn"); return 0; } 

Arduino代码是:

 #include  #include  //Mac and Ip of Arduino byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192, 168, 1, 144); EthernetServer server(23); // Set Server Port boolean alreadyConnected = false; // whether or not the client was connected previously void setup() { Serial.begin(9600); // initialize the ethernet device Ethernet.begin(mac, ip); server.begin(); //print out the IP address Serial.print("IP = "); Serial.println(Ethernet.localIP()); } void loop() { // wait for a new client: EthernetClient client = server.available(); // when the client sends the first byte, say hello: if (client) { if (!alreadyConnected) { // clear out the input buffer: client.flush(); Serial.println("We have a new client"); client.println("Hello, client!"); alreadyConnected = true; } if (client.available() > 0) { // read the bytes incoming from the client: char thisChar = client.read(); // echo the bytes back to the client: server.write(thisChar); // echo the bytes to the server as well: Serial.write(thisChar); } } } 

我做错了什么? 谢谢!

      以上就是c/c++开发分享关于Arduino上TCP的问题相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522053.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐