我会让球滚动:
import socket
import struct
username = "username_value"
verification_key = "verification_key"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # boilerplate
s.connect(("example.com", 1234)) # adjust accordingly
# now for the packet
# note that the String type is specified as having a length of 64, we'll pad that
packet = ""
packet += struct.pack("B", 1) # packet type
packet += struct.pack("B", 7) # protocol version
packet += "%-64s" % username # magic!
packet += "%-64s" % verification_key
packet += struct.pack("B", 0) # that unused byte, assuming a NULL byte here
# send what we've crafted
s.send(packet)
如果您从未使用过格式字符串,“%-20s”可能对您来说很奇怪。本质上..
print "%s" % 5
.. 会打印出 5 ..
print "%10s" % 5
.. 会将输出填充为正好 10 个字符的宽度。但它在右侧填充它们,我们希望在左侧填充 - 因此-
..
print "%-10s" % s, "<this will be 9 spaces away from the '5'>"
..玩弄它。
如果有任何不清楚的地方,请告诉我。我喜欢你在做的事情,让我想起了我的一个旧项目。除了我没有像你那样简洁的协议规范,幸运的混蛋。;)