Commit a0070c99ea4c9669f198f85e06d84003c5a4d3be

Authored by Wiebe Cazemier
1 parent 8ddb61d6

Improve disconnect handling

client.cpp
@@ -21,17 +21,18 @@ Client::~Client() @@ -21,17 +21,18 @@ Client::~Client()
21 { 21 {
22 Logger *logger = Logger::getInstance(); 22 Logger *logger = Logger::getInstance();
23 logger->logf(LOG_NOTICE, "Removing client '%s'", repr().c_str()); 23 logger->logf(LOG_NOTICE, "Removing client '%s'", repr().c_str());
  24 + if (epoll_ctl(threadData->epollfd, EPOLL_CTL_DEL, fd, NULL) != 0)
  25 + logger->logf(LOG_ERR, "Removing fd %d of client '%s' from epoll produced error: %s", fd, repr().c_str(), strerror(errno));
24 close(fd); 26 close(fd);
25 } 27 }
26 28
27 -// Do this from a place you'll know ownwership of the shared_ptr is being given up everywhere, so the close happens when the last owner gives it up. 29 +// Causes future activity on the client to cause a disconnect.
28 void Client::markAsDisconnecting() 30 void Client::markAsDisconnecting()
29 { 31 {
30 if (disconnecting) 32 if (disconnecting)
31 return; 33 return;
32 34
33 disconnecting = true; 35 disconnecting = true;
34 - check<std::runtime_error>(epoll_ctl(threadData->epollfd, EPOLL_CTL_DEL, fd, NULL));  
35 } 36 }
36 37
37 // false means any kind of error we want to get rid of the client for. 38 // false means any kind of error we want to get rid of the client for.
mqttpacket.cpp
@@ -110,6 +110,8 @@ void MqttPacket::handle() @@ -110,6 +110,8 @@ void MqttPacket::handle()
110 110
111 if (packetType == PacketType::CONNECT) 111 if (packetType == PacketType::CONNECT)
112 handleConnect(); 112 handleConnect();
  113 + else if (packetType == PacketType::DISCONNECT)
  114 + handleDisconnect();
113 else if (packetType == PacketType::PINGREQ) 115 else if (packetType == PacketType::PINGREQ)
114 sender->writePingResp(); 116 sender->writePingResp();
115 else if (packetType == PacketType::SUBSCRIBE) 117 else if (packetType == PacketType::SUBSCRIBE)
@@ -247,6 +249,15 @@ void MqttPacket::handleConnect() @@ -247,6 +249,15 @@ void MqttPacket::handleConnect()
247 } 249 }
248 } 250 }
249 251
  252 +void MqttPacket::handleDisconnect()
  253 +{
  254 + logger->logf(LOG_NOTICE, "Client '%s' cleanly disconnecting", sender->repr().c_str());
  255 + sender->markAsDisconnecting();
  256 + sender->getThreadData()->removeClient(sender);
  257 +
  258 + // TODO: clear will
  259 +}
  260 +
250 void MqttPacket::handleSubscribe() 261 void MqttPacket::handleSubscribe()
251 { 262 {
252 uint16_t packet_id = readTwoBytesToUInt16(); 263 uint16_t packet_id = readTwoBytesToUInt16();
mqttpacket.h
@@ -57,6 +57,7 @@ public: @@ -57,6 +57,7 @@ public:
57 57
58 void handle(); 58 void handle();
59 void handleConnect(); 59 void handleConnect();
  60 + void handleDisconnect();
60 void handleSubscribe(); 61 void handleSubscribe();
61 void handlePing(); 62 void handlePing();
62 void handlePublish(); 63 void handlePublish();