Skip to content

Commit 32a9d84

Browse files
authored
Merge pull request #149 from jandrassy/PagerServer_example
PagerServer example to show how server.available() and server.print() really works
2 parents 473cfeb + 235da47 commit 32a9d84

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

examples/PagerServer/PagerServer.ino

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Pager Server
3+
4+
A simple server that echoes any incoming messages to all
5+
connected clients. Connect two or more telnet sessions
6+
to see how server.available() and server.print() works.
7+
8+
created in September 2020 for the Ethernet library
9+
by Juraj Andrassy https://github.com/jandrassy
10+
11+
*/
12+
#include <Ethernet.h>
13+
14+
// Enter a MAC address for your controller below.
15+
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
16+
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
17+
18+
// Set the static IP address to use if the DHCP fails to assign
19+
IPAddress ip(192, 168, 0, 177);
20+
21+
EthernetServer server(2323);
22+
23+
void setup() {
24+
25+
Serial.begin(9600);
26+
while (!Serial);
27+
28+
// start the Ethernet connection:
29+
Serial.println("Initialize Ethernet with DHCP:");
30+
if (Ethernet.begin(mac) == 0) {
31+
Serial.println("Failed to configure Ethernet using DHCP");
32+
// Check for Ethernet hardware present
33+
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
34+
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
35+
while (true) {
36+
delay(1); // do nothing, no point running without Ethernet hardware
37+
}
38+
}
39+
if (Ethernet.linkStatus() == LinkOFF) {
40+
Serial.println("Ethernet cable is not connected.");
41+
}
42+
// try to congifure using IP address instead of DHCP:
43+
Ethernet.begin(mac, ip);
44+
} else {
45+
Serial.print(" DHCP assigned IP ");
46+
Serial.println(Ethernet.localIP());
47+
}
48+
49+
server.begin();
50+
51+
IPAddress ip = Ethernet.localIP();
52+
Serial.println();
53+
Serial.print("To access the server, connect with Telnet client to ");
54+
Serial.print(ip);
55+
Serial.println(" 2323");
56+
}
57+
58+
void loop() {
59+
60+
EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client
61+
if (client) { // client is true only if it is connected and has data to read
62+
String s = client.readStringUntil('\n'); // read the message incoming from one of the clients
63+
s.trim(); // trim eventual \r
64+
Serial.println(s); // print the message to Serial Monitor
65+
client.print("echo: "); // this is only for the sending client
66+
server.println(s); // send the message to all connected clients
67+
server.flush(); // flush the buffers
68+
}
69+
}

0 commit comments

Comments
 (0)