elhayra / tcp_server_client

A thin and simple C++ TCP client server
MIT License
155 stars 53 forks source link

bug: msg size wrong #14

Open IOTeule opened 2 years ago

IOTeule commented 2 years ago

There seems to be a bug in the server example about incoming msg size.

To reproduce:

  1. build master
  2. start client_example and server_example
  3. client: send message '1234356'
  4. server receives '123456'
  5. client send message ' 4'
  6. server receives '423456', but should be '4' only

seems to be a bug in message size

IOTeule commented 2 years ago

I think, this should fix it:

void Client::receiveTask() {
    while(isConnected()) {
        const fd_wait::Result waitResult = fd_wait::waitFor(_sockfd);

        if (waitResult == fd_wait::Result::FAILURE) {
            throw std::runtime_error(strerror(errno));
        } else if (waitResult == fd_wait::Result::TIMEOUT) {
            continue;
        }

        char receivedMessage[MAX_PACKET_SIZE];
        const size_t numOfBytesReceived = recv(_sockfd.get(), receivedMessage, MAX_PACKET_SIZE, 0);

        if(numOfBytesReceived < 1) {
            const bool clientClosedConnection = (numOfBytesReceived == 0);
            std::string disconnectionMessage;
            if (clientClosedConnection) {
                disconnectionMessage = "Client closed connection";
            } else {
                disconnectionMessage = strerror(errno);
            }
            setConnected(false);
            publishEvent(ClientEvent::DISCONNECTED, disconnectionMessage);
            return;
        } else {
            // fix here
            receivedMessage[numOfBytesReceived] = '\0';
            // fix here
            publishEvent(ClientEvent::INCOMING_MSG, receivedMessage);
        }
    }
}
IOTeule commented 2 years ago

see PR