serversocket.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #include "serversocket.h"
  2. #include "clientsocket.h"
  3. ServerSocket::ServerSocket(QObject *parent) :
  4. QObject(parent)
  5. {
  6. iUdpBroadcastSocket = 0;
  7. iTcpServer = 0;
  8. iTimerId = -1;
  9. udpOnly = false;
  10. iWantedToStart = false;
  11. QTimer::singleShot(2000,this,SLOT(startNetwork()));
  12. }
  13. void ServerSocket::startNetwork()
  14. {
  15. //writeLog("Finds networks");
  16. // TODO: Should clinetsocket.cpp have also QNetworkConfigurationManager?
  17. iNetworkManager = new QNetworkConfigurationManager(this);
  18. /*
  19. QObject::connect(iNetworkManager, SIGNAL(updateCompleted()), this, SLOT(networkUpdated()));
  20. iNetworkManager->updateConfigurations();
  21. #ifdef Q_WS_SIMULATOR
  22. networkUpdated();
  23. #endif
  24. */
  25. QNetworkConfiguration cfg = iNetworkManager->defaultConfiguration();
  26. iNetworkSession = new QNetworkSession(cfg,this);
  27. iNetworkSession->open();
  28. iNetworkSession->waitForOpened();
  29. iServerAddress = this->findServerAddress();
  30. if (iWantedToStart) {
  31. start();
  32. }
  33. }
  34. void ServerSocket::networkUpdated()
  35. {
  36. if (!iNetworkSession) {
  37. // QList<QNetworkConfiguration> configs = iNetworkManager->allConfigurations(QNetworkConfiguration::Discovered);
  38. QList<QNetworkConfiguration> configs = iNetworkManager->allConfigurations();
  39. foreach(QNetworkConfiguration conf, configs) {
  40. qDebug() << "-----------NET----------";
  41. qDebug() << "Name: " << conf.name();
  42. qDebug() << "Bearer type: " << conf.bearerTypeName();
  43. qDebug() << "Bearer type: " << conf.type();
  44. qDebug() << "State: " << conf.state();
  45. qDebug() << "Valid: " << conf.isValid();
  46. qDebug() << "Purpose: " << conf.purpose();
  47. qDebug() << "Identifier: " << conf.identifier();
  48. #if defined Q_OS_SYMBIAN
  49. // if ( conf.isValid() && conf.purpose() == QNetworkConfiguration::PublicPurpose &&
  50. if ( conf.isValid() &&
  51. conf.bearerType() == QNetworkConfiguration::BearerWLAN) {
  52. #elif defined Q_WS_SIMULATOR
  53. if ( conf.isValid() &&
  54. conf.bearerType() == QNetworkConfiguration::BearerEthernet ) {
  55. #endif
  56. iNetworkSession = new QNetworkSession(conf, this);
  57. writeLog("Try to open: "+conf.name());
  58. iNetworkSession->open();
  59. iNetworkSession->waitForOpened(10000);
  60. if(iNetworkSession->isOpen()) {
  61. iServerAddress = this->findServerAddress();
  62. if (iWantedToStart) {
  63. start();
  64. break;
  65. }
  66. } else {
  67. writeLog("Could not open: "+conf.name());
  68. delete iNetworkSession;
  69. iNetworkSession = 0;
  70. }
  71. }
  72. }
  73. }
  74. if(!iNetworkSession) {
  75. // TODO: no connection
  76. writeLog("NOT connected to network");
  77. }
  78. }
  79. ServerSocket::~ServerSocket()
  80. {
  81. stop();
  82. }
  83. bool ServerSocket::UdpOnly()
  84. {
  85. return udpOnly;
  86. }
  87. void ServerSocket::setUdpOnly(bool udb)
  88. {
  89. udpOnly = udb;
  90. }
  91. void ServerSocket::start()
  92. {
  93. //writeLog("Try to start Server");
  94. if (!iNetworkSession) {
  95. // Network not open. Open later when network exists at networkUpdated()
  96. iWantedToStart = true;
  97. return;
  98. }
  99. if (!iTcpServer) {
  100. // Start TCP server
  101. if (iNetworkSession && iNetworkSession->isOpen()) {
  102. // Server for listening Client
  103. // ** TCP **
  104. iTcpServer = new QTcpServer(this);
  105. if (!udpOnly && iTcpServer->listen(QHostAddress::Any, SERVER_PORT)) {
  106. QObject::connect(iTcpServer, SIGNAL(newConnection()), this, SLOT(establishClientConnection()));
  107. writeLog(QString("Server listening on port: %1").arg(iTcpServer->serverPort()));
  108. // Start broadcasting server IP periodically to Clients
  109. if (!iUdpBroadcastSocket) {
  110. iUdpBroadcastSocket = new QUdpSocket(this);
  111. iTimerId = this->startTimer(4000); // Broadcast IP
  112. }
  113. writeLog("Started");
  114. }
  115. else if (udpOnly) {
  116. // ** UDP **
  117. // Start broadcasting server IP periodically to Clients
  118. if (!iUdpBroadcastSocket) {
  119. iUdpBroadcastSocket = new QUdpSocket(this);
  120. QObject::connect(iUdpBroadcastSocket, SIGNAL(readyRead()),this, SLOT(udpGetData()));
  121. iTimerId = this->startTimer(4000); // Broadcast hello
  122. }
  123. }
  124. } else {
  125. writeLog("NOT started");
  126. }
  127. } else {
  128. writeLog("Already started");
  129. }
  130. }
  131. void ServerSocket::stop()
  132. {
  133. this->killTimer(iTimerId);
  134. iTimerId = -1;
  135. if (iTcpServer) {
  136. iTcpServer->close();
  137. //delete iTcpServer;
  138. iTcpServer = 0;
  139. }
  140. if (iUdpBroadcastSocket) {
  141. iUdpBroadcastSocket->close();
  142. //delete iUdpBroadcastSocket;
  143. iUdpBroadcastSocket = 0;
  144. }
  145. if (iNetworkSession) {
  146. iNetworkSession->close();
  147. //delete iNetworkSession;
  148. iNetworkSession = 0;
  149. }
  150. }
  151. void ServerSocket::writeLog(QString log)
  152. {
  153. log = log.prepend("[Server] ");
  154. qDebug() << log;
  155. emit serverLog(log);
  156. }
  157. void ServerSocket::timerEvent(QTimerEvent* e)
  158. {
  159. if (iTimerId == e->timerId()) {
  160. if (udpOnly) {
  161. sendToClient("UDP Hello from Server");
  162. } else {
  163. broadcast();
  164. }
  165. }
  166. }
  167. QString ServerSocket::findServerAddress()
  168. {
  169. QString ret;
  170. if (iNetworkSession && iNetworkSession->isOpen()) {
  171. // Go through all interfaces and add all IPs for interfaces that
  172. // can broadcast and are not local.
  173. foreach (QNetworkInterface qni, QNetworkInterface::allInterfaces() ) {
  174. if (!qni.addressEntries().isEmpty() && qni.isValid()) {
  175. QNetworkInterface::InterfaceFlags fl = qni.flags();
  176. if ( fl & QNetworkInterface::IsUp &&
  177. fl & QNetworkInterface::IsRunning &&
  178. fl & QNetworkInterface::CanBroadcast &&
  179. fl & QNetworkInterface::CanMulticast && // TODO: ?????
  180. !(fl & QNetworkInterface::IsLoopBack) ) {
  181. ret = qni.addressEntries().at(0).ip().toString();
  182. foreach(QNetworkAddressEntry e, qni.addressEntries())
  183. {
  184. qDebug() << e.ip().toString();
  185. ret = e.ip().toString();
  186. }
  187. return ret;
  188. }
  189. }
  190. }
  191. }
  192. return ret;
  193. }
  194. void ServerSocket::broadcast()
  195. {
  196. QString msg = QString(SERVER_ID) + "@"+ iServerAddress;
  197. QByteArray datagram;
  198. datagram.append(msg);
  199. iUdpBroadcastSocket->writeDatagram(datagram.data(), datagram.size(),
  200. QHostAddress::Broadcast, SERVER_PORT);
  201. writeLog("Broadcast: "+msg);
  202. }
  203. void ServerSocket::establishClientConnection()
  204. {
  205. writeLog("Client tries to connect to the Server");
  206. iClientCommSocket = iTcpServer->nextPendingConnection();
  207. if (iClientCommSocket) {
  208. writeLog(QString("Client address: %1").arg(iClientCommSocket->peerAddress().toString()));
  209. writeLog(QString("Client port: %1").arg(iClientCommSocket->peerPort()));
  210. emit clientConnected(iClientCommSocket->peerAddress().toString(),iClientCommSocket->peerPort());
  211. QObject::connect(iClientCommSocket, SIGNAL(readyRead()), this, SLOT(readClientTcpData()));
  212. // Stop broadcasting
  213. this->killTimer(iTimerId);
  214. iTimerId = -1;
  215. sendToClient("Hello from Server");
  216. } else {
  217. writeLog("No pending connections");
  218. }
  219. }
  220. void ServerSocket::readClientTcpData()
  221. {
  222. QString msg(iClientCommSocket->readAll());
  223. writeLog("From Client: "+msg);
  224. }
  225. void ServerSocket::udpGetData()
  226. {
  227. while (iUdpBroadcastSocket->hasPendingDatagrams()) {
  228. QByteArray datagram;
  229. datagram.resize(iUdpBroadcastSocket->pendingDatagramSize());
  230. iUdpBroadcastSocket->readDatagram(datagram.data(), datagram.size());
  231. if (udpOnly && datagram.startsWith(CLIENT_ID)) {
  232. QString data(datagram);
  233. writeLog("From UDP: "+data);
  234. }
  235. break;
  236. }
  237. }
  238. void ServerSocket::sendToClient(QString msg)
  239. {
  240. QByteArray datagram;
  241. if (udpOnly) {
  242. datagram.append(QString(SERVER_ID));
  243. datagram.append(msg);
  244. iUdpBroadcastSocket->writeDatagram(datagram.data(), datagram.size(),
  245. QHostAddress::Broadcast, SERVER_PORT);
  246. } else {
  247. datagram.append(msg);
  248. iClientCommSocket->write(datagram);
  249. }
  250. writeLog("To Client: "+msg);
  251. }