C++ Server Cannot Read My Message From Python Client Via Socket
Solution 1:
Like Galik already said, Python doesn't send the length of the string before the string, like your programm expects it. And C/C++ doesn't do this either.
If you want your Python program to work with your C programm, there are several things you have to consider:
- Use the
struct
module to pack your string with the required length before it - Use the network byte order when packing your string
- You should be aware that declarations like
size_t
are architecture dependant and vary between 64 and 32 bit architectures. You can use fixed size integers likeuint32_t
if you want them to be compatible between architectures.
Example Code:
from structimport pack
message = "Hello World"
data = pack('!i%ds' % len(message), len(message), message))
If you can't change the C-Code to use the network byte order, your specific code should look like this:
from structimport pack
message = "Hello World"
data = pack('<Q%ds' % len(message), len(message), message))
<
= Use little endian byte order
Q
= Use an unsigned 64 bit integer (sizet_t
on 64Bit architectures)
Solution 2:
As Galik pointed out your python script does not send any length of the message. While your c++ server reads 4 bytes ( 8 if you are on 64 bit linux ) and expect them to be length of the message. So first 4 bytes are "Hell" which binary form will be quite a big number of bytes your server tries to read.
To fix this - send first 4 bytes as message length in your python script. Also you'll need to use network byte order ( if you plan to stuck with binary ) to make sure bytes read properly. Use ntohl() function to convert from network to host byte order number.
Post a Comment for "C++ Server Cannot Read My Message From Python Client Via Socket"