hello; i am trying to connect a server ; i am using the following code;in general it fails to connect , although it sometimes connects. can anyone show what the problem is.
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x19, 0xC4 };
byte ip[] = { 192, 168, 2, 240 };
byte serverIp[] = { 192, 168, 2, 5 };
int backPortNo = 1292;
EthernetClient client;
EthernetServer backPortServer(backPortNo);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
backPortServer.begin();
Serial.print("Backport open:");
Serial.print(Ethernet.localIP());
Serial.print(":");
Serial.println(backPortNo);
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.print("Server:");
// if you get a connection, report back via serial:
if (client.connect(serverIp, 10000)) {
Serial.println("connected");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// as long as there are bytes in the serial queue,
// read them and send them out the socket if it's open:
while (Serial.available() > 0) {
char inChar = Serial.read();
if (client.connected()) {
client.print(inChar);
}
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing:
while(true);
}
// }
}