其他分享
首页 > 其他分享> > hexdump(b,step,sep,decimal) 和 server、client 端 [北极星]

hexdump(b,step,sep,decimal) 和 server、client 端 [北极星]

作者:互联网

server端 代码

import socket
HOST=""
PORT=50007
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.bind((HOST,PORT))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
print("Connected by", addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.shutdown(socket.SHUT_RDWR)
conn.close()
************************************************************************

client端 代码
import socket
HOST="localhost"
PORT=50007
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
data=b"Hello, Python"
s.sendall(data)
data2=s.recv(1024)
print("Received",repr(data2))
************************************************************************

字节流转换16进制代码
def hexdump(b,step=16,sep=4,decimal=False):
    for i in range(0, len(b), step):
sub = b[i:i + step]
output = "%08x" % i
output += " %08d" % i if decimal else ""
output += " | "

temp = " ".join(["%02x" % c for c in sub])
temp += " " * (step - len(sub))
output += " ".join([temp[j:j + sep * 3] for j in range(0, len(temp), sep * 3)])

output += " | "
output += "".join([chr(c) if 0x20 <= c < 0x7F else "." for c in sub])

print(output)

text=b"I Love You, My Friend!"
hexdump(text,8,4,True)
------------------------------------------------------------------------------------------

00000000 00000000 | 49 20 4c 6f 76 65 20 59 | I Love Y
00000008 00000008 | 6f 75 2c 20 4d 79 20 46 | ou, My F
00000010 00000016 | 72 69 65 6e 64 21          | riend!

标签:hexdump,20,socket,sep,decimal,step,output,data,conn
来源: https://www.cnblogs.com/daodantou/p/10427052.html