//
#include "plaqui/server/receiver.h"
+#include <sstream>
#ifdef DEBUG
# include <iostream>
#endif // DEBUG
namespace Server {
+const string Receiver::FRAME_BEGIN("<plantstatus");
+
+const string Receiver::FRAME_END("</plantstatus>");
+
Receiver::~Receiver(void) {
#ifdef DEBUG
- cerr << __FILE__ << ": destructor." << endl;
+ cerr << __FILE__ << "(" << __LINE__ << ")"
+ << ": destructor." << endl;
#endif // DEBUG
}
-Receiver::Receiver(int port, string host): Connection(sockbuf::sock_dgram) {
+Receiver::Receiver(const Connection::Port& port, const string& host)
+ throw(sockerr): Connection(sockbuf::sock_dgram, host, port) {
#ifdef DEBUG
- cerr << __FILE__ << ": port = " << port
+ cerr << __FILE__ << "(" << __LINE__ << ")"
+ << ": port = " << port
<< " | host = " << host << endl;
#endif // DEBUG
- // FIXME - deberia ir en run().
- socket->bind(port);
+ socket->bind(host.c_str(), port);
}
-void Receiver::real_run(void) {
+// XXX EL XML DEBE EMPEZAR Y FINALIZAR EN UNA LINEA SEPARADA.
+void Receiver::real_run(void) throw() {
#ifdef DEBUG
- cerr << __FILE__ << ": real_run." << endl;
+ cerr << __FILE__ << "(" << __LINE__ << ")"
+ << ": real_run." << endl;
#endif // DEBUG
- // FIXME - debería tirar una excepción?
- if (!socket->is_open()) {
- cerr << "No se pudo conectar a " << socket->peerhost() <<
- ":" << socket->peerport() << "." << endl;
- } else {
- cerr << "Conectado a " << socket->peerhost() <<
- ":" << socket->peerport() << "." << endl;
+ char buf[BUFSIZ];
+ bool in_frame = false;
+ stringstream ss;
+ while (!stop()) {
+ try {
+ if (!socket.getline(buf, BUFSIZ)) {
+ return; // Se terminó la transmision.
+ }
+ } catch (const sockerr& e) {
+ signal_error().emit(e.serrno(), e.errstr());
+ return;
+ }
+ string sbuf = buf;
+ if (in_frame) {
+ string::size_type pos = sbuf.find(FRAME_END);
+ if (pos == string::npos) { // No encuentra el fin
+ ss << sbuf << endl;
+ } else { // Encuentra el fin.
+ // Agrego al mensaje actual hasta el final </plantstatus>.
+ ss << sbuf.substr(0, pos + FRAME_END.length());
+ frame_received(ss.str());
+ ss.str("");
+ in_frame = false;
+ }
+ } else { // No esta en un frame.
+ string::size_type pos = sbuf.find(FRAME_BEGIN);
+ if (pos != string::npos) { // Encuentra el inicio
+ ss << sbuf.substr(pos) << endl;
+ in_frame = true;
+ }
+ }
}
}
+Receiver::SignalFrameReceived& Receiver::signal_frame_received(void) {
+ return frame_received;
+}
+
} // namespace Server
} // namespace PlaQui