2
2
Chat Server
3
3
4
4
A simple server that distributes any incoming messages to all
5
- connected clients. To use telnet to your device's IP address and type.
5
+ connected clients but the client the message comes from.
6
+ To use telnet to your device's IP address and type.
6
7
You can see the client's input in the serial monitor as well.
7
8
Using an Arduino Wiznet Ethernet shield.
8
9
14
15
by David A. Mellis
15
16
modified 9 Apr 2012
16
17
by Tom Igoe
18
+ redesigned to make use of operator== 25 Nov 2013
19
+ by Norbert Truchsess
17
20
18
21
*/
19
22
25
28
// gateway and subnet are optional:
26
29
byte mac[] = {
27
30
0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED };
28
- IPAddress ip (192 ,168 ,1 , 177 );
29
- IPAddress gateway (192 ,168 ,1 , 1 );
30
- IPAddress subnet (255 , 255 , 0 , 0 );
31
+ IPAddress ip (192 ,168 ,0 , 6 );
32
+ IPAddress gateway (192 ,168 ,0 , 1 );
33
+ IPAddress subnet (255 , 255 , 255 , 0 );
31
34
32
35
33
36
// telnet defaults to port 23
34
37
EthernetServer server (23 );
35
- boolean alreadyConnected = false ; // whether or not the client was connected previously
38
+
39
+ EthernetClient clients[4 ];
36
40
37
41
void setup () {
38
42
// initialize the ethernet device
@@ -54,26 +58,55 @@ void loop() {
54
58
// wait for a new client:
55
59
EthernetClient client = server.available ();
56
60
57
- // when the client sends the first byte, say hello:
58
61
if (client) {
59
- if (!alreadyConnected) {
62
+
63
+ boolean newClient = true ;
64
+ for (byte i=0 ;i<4 ;i++) {
65
+ if (clients[i]==client) {
66
+ newClient = false ;
67
+ break ;
68
+ }
69
+ }
70
+
71
+ if (newClient) {
72
+ for (byte i=0 ;i<4 ;i++) {
73
+ if (clients[i]!=client) {
74
+ clients[i] = client;
75
+ Serial.print (" found slot: " );
76
+ Serial.println (i);
77
+ break ;
78
+ }
79
+ }
80
+
60
81
// clead out the input buffer:
61
82
client.flush ();
62
83
Serial.println (" We have a new client" );
63
84
client.println (" Hello, client!" );
64
- alreadyConnected = true ;
65
- }
85
+ client.print (" your IP: " );
86
+ client.println (client.remoteIP ());
87
+ client.print (" your port: " );
88
+ client.println (client.remotePort ());
89
+ }
66
90
67
91
if (client.available () > 0 ) {
68
92
// read the bytes incoming from the client:
69
93
char thisChar = client.read ();
70
94
// echo the bytes back to the client:
71
- server.write (thisChar);
95
+ for (byte i=0 ;i<4 ;i++) {
96
+ if (!clients[i] || (clients[i]==client)) {
97
+ continue ;
98
+ }
99
+ clients[i].write (thisChar);
100
+ }
72
101
// echo the bytes to the server as well:
73
102
Serial.write (thisChar);
74
103
}
75
104
}
105
+ for (byte i=0 ;i<4 ;i++) {
106
+ if (!(clients[i].connected ())) {
107
+ clients[i].stop ();
108
+ ~clients[i];
109
+ clients[i]=EthernetClient ();
110
+ }
111
+ }
76
112
}
77
-
78
-
79
-
0 commit comments