1

I have a CPP server and python3 client but when I'm sending data I'm getting garbage values (wrong numbers and \0 in the middle of the string) i tried to use this answer and also C++ TCP socket garbage value.

the client code (python3):

MESSAGE = "HELLO WORLD"
def send_via_socket(message):
    print(len(message))
    s.send(bytes([len(message)]))
    data = pack('<Q%ds' % len(message), len(message), message.encode())
    s.send(data)
    return True

SERVER_IP = "127.0.0.1"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Create a socket object
ans = s.connect((SERVER_IP, PORT))
if ans is None:
     write_to_log('connection to server establish')
     send_via_socket(MESSAGE)
else:
     write_to_log('connection failed')
     message = s.recv(1024)
     write_to_log(str(message, 'utf-8'))
     res = res
except socket.error as err:
    message = f"socket creation failed with error %s" % err
    write_to_log(message)
    return res

and the read function in the server (cpp)

int Server::readString(int fd, std::string &str)
{
    size_t len;
    char *buf;

    auto bytesReceived =read(fd, &len, sizeof(len));
    if(bytesReceived == -1)
    {
        return bytesReceived;
    }
    buf = new char[len];
    bytesReceived = read(fd, buf, len);
    if(bytesReceived == -1)
    {
        return bytesReceived;
    }

    str.assign(buf, len);
    delete []buf;
    return bytesReceived;
}

I also have a CPP client and its work fine

3 Answers 3

1

the answer that I found at the end was using Oleguer Canal functions

its solves all the garbage problome

Sign up to request clarification or add additional context in comments.

1 Comment

Holly shit, just saw you linked my repo! Happy to be useful :)
0

This might fail, once the length of the encoded message is not equal to the length of the original message -- happens a lot, once you start sending UTF-8 or anything besides plain ASCII:

data = pack('<Q%ds' % len(message), len(message), message.encode())

You might be better off using protobuf or something like ZeroMQ for sending your data. Easy to implement in any language, and you don't have to count bytes anymore.

Comments

0
s.send(bytes([len(message)]))

Sends the length as a single byte.

auto bytesReceived =read(fd, &len, sizeof(len));

Reads the length as a size_t, which is more than a single byte.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.