Reputation: 1681
I am trying to translate some c++ codes to python which send some data to a java server.
The origin c++ code is as follow :
std::string msgstr = "";
msg.SerializeToString(&msgstr);
auto allocSize = msgstr.size() + 1024;
char* data = (char*)malloc(allocSize);
uLong gzlen = msgstr.size() + 1024;
Bytef*pCompressData = (Bytef*)malloc(gzlen);
auto result = CGameZipUtils::gzcompress(/**/);
if(result == 0) {
int tmp;
tmp = htonl((int)gzlen);
memcpy(&data[0], &tmp, 4);
memcpy(&data[4], pCompressData, gzlen);
sendData(data,(int)gzlen + 4);
}
Now I used the zlib and socket package in python and so far I seem to have the compress part working because the output of the data length in python now is as same as in C++:
msgstr = msg.SerializeToString()
print "msgstr: %s" % len(msgstr)
gzlen = len(msgstr) + 1024
compressor = zlib.compressobj(-1, zlib.DEFLATED, 31, 8, zlib.Z_DEFAULT_STRATEGY)
pCompressData = compressor.compress(msgstr)
pCompressData += compressor.flush()
gzlen = len(pCompressData)
print "gzlen: %s" % gzlen
tmp = socket.htonl(gzlen)
print "tmp: %s" % tmp
The problem I am having now is that I do not know how to send the data I get from zlib.compress and add a head with data length to it then send the data to my server.
I need to figured out how to write the data to send :
send = "??????"
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((GATE_ADDRESS, GATE_PORT))
client_socket.send(data)
client_socket.close()
Any advice will be appreciated, thanks :)
Upvotes: 0
Views: 691
Reputation: 1681
Find out the solution my self finally:
data = struct.pack('i', tmp)
//...
client_socket.send(data + pCompressData)
Upvotes: 1