You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.4 KiB
70 lines
1.4 KiB
/*
|
|
|
|
Simple state machine-based Echo Server.
|
|
|
|
This could be used as the base for a more sophisticated server
|
|
that filtered the returned input, or altered state on the microcontroller
|
|
in response to the incoming data.
|
|
|
|
*/
|
|
|
|
#include "libw5100.h"
|
|
|
|
#include "echo_server.h"
|
|
|
|
#define ECHO_CONNECT_WAIT 0
|
|
#define ECHO_CONNECTED 1
|
|
#define ECHO_CLOSE 2
|
|
#define ECHO_HALT 3
|
|
|
|
EchoServer::EchoServer(int port) : _connection (NetworkConnection(port)) {
|
|
/*
|
|
|
|
Create a listening echo server on the requested port.
|
|
|
|
*/
|
|
|
|
_state = ECHO_CONNECT_WAIT;
|
|
|
|
_connection.listen(); // TODO: We should be using Network.listen(...) here and in initialisation list.
|
|
}
|
|
|
|
void EchoServer::next() {
|
|
/*
|
|
|
|
Process incoming data and return it to the sender.
|
|
|
|
*/
|
|
|
|
// TODO: Use better state machine implementation?
|
|
|
|
if (_state == ECHO_CONNECT_WAIT) {
|
|
|
|
if (_connection.isConnected()) {
|
|
_state = ECHO_CONNECTED;
|
|
} else {
|
|
// Keep waiting
|
|
}
|
|
|
|
} else if (_state == ECHO_CONNECTED) {
|
|
|
|
if (_connection.available()) {
|
|
_connection.print(_connection.read());
|
|
} else if (!_connection.isConnected()) {
|
|
// Data finished and client disconnected
|
|
_state == ECHO_CLOSE;
|
|
}
|
|
|
|
} else if (_state == ECHO_CLOSE) {
|
|
|
|
_connection.close();
|
|
_state = ECHO_HALT;
|
|
|
|
} else if (_state == ECHO_HALT) {
|
|
// Do nothing
|
|
} else {
|
|
// Unknown state, do nothing.
|
|
}
|
|
}
|
|
|