python struct

在使用python向java发送数据的时候一般是需要记录数据长度的,数据长度应该是int类型:

s = socket.socket()
s.connect((host, port))
data = 'hello world'
s.sendall('%16s' % len(data)) #send data length
s.sendall(data) #send data
s.close()

但python 如何发送int类型?答案是使用struct。

Java expects the binary representation of your integer. You can use the struct module to generate binary representations.

In your case, this would be:

import struct
s.sendall(struct.pack('>i', len(data)))
 
第一个参数'>i'分别表示使用big-endian和int类型。

Also make sure you use the correct byte order . Java could be expecting network byte order.

详见:http://stackoverflow.com/questions/10228927/how-to-send-an-integer-over-a-socket-to-a-java-application-using-python

http://www.cnblogs.com/zhangjing0502/archive/2012/05/15/2501010.html

猜你喜欢

转载自san-yun.iteye.com/blog/1718336
今日推荐