From 5a79899d5a888e9aa76f29cb889e77979062a4a1 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 15 Oct 2015 02:49:29 +0300 Subject: [PATCH] Use a datagram socket for automatic service discovery --- source/networkinterface.cpp | 16 ++++++++++++++++ source/networkinterface.h | 3 +++ 2 files changed, 19 insertions(+) diff --git a/source/networkinterface.cpp b/source/networkinterface.cpp index 74c80dc..1bf7b4a 100644 --- a/source/networkinterface.cpp +++ b/source/networkinterface.cpp @@ -6,17 +6,23 @@ using namespace std; using namespace Msp; +#include + NetworkInterface::NetworkInterface(Xinema &x): xinema(x) { Net::SockAddr *addr = Net::resolve("::", "34588", Net::INET6); server_sock = new Net::StreamServerSocket(addr->get_family()); server_sock->listen(*addr); + discover_sock = new Net::DatagramSocket(addr->get_family()); + discover_sock->bind(*addr); delete addr; server_sock->signal_data_available.connect(sigc::mem_fun(this, &NetworkInterface::connection_available)); + discover_sock->signal_data_available.connect(sigc::mem_fun(this, &NetworkInterface::discover_request)); event_disp.add(*server_sock); + event_disp.add(*discover_sock); thread = new NetworkThread(*this); } @@ -35,6 +41,16 @@ void NetworkInterface::connection_available() clients.push_back(new Client(xinema, sock)); } +void NetworkInterface::discover_request() +{ + Net::SockAddr *peer_addr; + char rbuf[1024]; + discover_sock->recvfrom(rbuf, sizeof(rbuf), peer_addr); + IO::print("Discovery beacon received from %s\n", peer_addr->str()); + discover_sock->sendto("xinema", 6, *peer_addr); + delete peer_addr; +} + NetworkInterface::NetworkThread::NetworkThread(NetworkInterface &n): network(n), diff --git a/source/networkinterface.h b/source/networkinterface.h index fbb66b9..9814f6a 100644 --- a/source/networkinterface.h +++ b/source/networkinterface.h @@ -4,6 +4,7 @@ #include #include #include +#include #include class Client; @@ -30,6 +31,7 @@ private: Xinema &xinema; Msp::Net::StreamServerSocket *server_sock; + Msp::Net::DatagramSocket *discover_sock; Msp::IO::EventDispatcher event_disp; NetworkThread *thread; std::list clients; @@ -40,6 +42,7 @@ public: private: void connection_available(); + void discover_request(); }; #endif -- 2.45.2