问题
I am experimenting with my Arduino Leonardo and a simple C socket server. The C part must send a string to the Arduino but I cannot connect to the arduino (after the socket is initialized C function is blocked and can not connect to Arduino). The C function code is:
#include <stdio.h>
#include <winsock2.h>
#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 Test\n";
if (send(s, message, strlen(message), 0) < 0) {
puts("Send failed");
return 1;
}
puts("Data Send\n");
return 0;
}
The Arduino code is:
#include <SPI.h>
#include <Ethernet.h>
//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);
}
}
}
What I'm doing wrong? Thank you!
来源:https://stackoverflow.com/questions/49350333/issues-with-tcp-on-arduino