Python网络应用基础笔记-网络字节顺序

1.服务器端代码,用来显示接收到的数据

# -*- coding: cp936 -*-
"""
服务器端接收客户端发送的数据,并显示出来
数据包定义:
typedef struct packet
{
    short l;
    short w;
    int h;
}
"""
import socket,struct
host = ""
port = 50000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
while 1:
    clientsock,clientaddr = s.accept()
    buf = clientsock.recv(8196)
    if len(buf) != 0:
        # 使用网络字节顺序进行解包
        data = struct.unpack("!hhl",buf)
        print(data)
    clientsock.shutdown(2)
    clientsock.close()
   
2.客户端代码,用来发送数据包
# -*- coding: cp936 -*-
"""
向服务端发送数据
数据包定义:
typedef struct packet
{
    short l;
    short w;
    int h;
}
"""
import socket,struct
host = "localhost"
port = 50000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
# 以网络字节顺序进行发送
s.send(struct.pack("!hhl",250,3754,61183))
s.close()