socket
module
import socket
TCP Server
HOST = ''
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
TCP Client
HOST = '192.168.2.52'
PORT = 60000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
UDP Server,
import socket
import sys
HOST = '' #INADDR_ANY
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind((HOST, PORT))
print("Listening %s:%d" % (HOST, PORT))
while True:
data, addr = s.recvfrom(1024)
print(data)
print(addr)
s.sendto(data, addr)
UDP Client
Example 1
HOST = '192.168.2.52'
PORT = 60001
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Example 2
import socket
import struct
HOST = '127.0.0.1'
PORT = 60000
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((HOST, PORT))
dataRequest = struct.pack(">hif", 64, 65536, 12.3)
print(f'Request: {dataRequest.hex()} {dataRequest}')
s.sendall(dataRequest)
dataReceive = s.recv(1024)
print(f'Received: {dataReceive.hex()} {dataReceive}')
Socket families
AF表示ADDRESS FAMILY 地址族,PF表示PROTOCOL FAMILY 协议族,在windows系统中,这两个宏定义是一样的,所以使用哪个都没有关系。
- socket.AF_UNIX(IPC本地进程间通信): The address of an AF_UNIX socket bound to a file system node is represented as a string
- socket.AF_INET(TCP/IP通信协议): A pair (host, port) is used for the AF_INET address family
socket.bind(address)
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like ‘daring.cwi.nl’ or an IPv4 address like ‘100.50.200.5’, and port is an integer.
For IPv4 addresses, two special forms are accepted instead of a host address: ‘’ represents INADDR_ANY, which is used to bind to all interfaces, and the string ‘
TCP & UDP
- TCP: SOCK_STREAM
- UDP: SOCK_DGRAM
byte 转int
byte_seq = b'\x00\x01' # 示例字节序列
int_val = int.from_bytes(byte_seq, byteorder='big') # 默认使用大端模式
print(int_val) # 输出: 256
struct
import struct
res = struct.pack("i",1234566) # 传入的必须是 int 类型
print(res) # b'\x86\xd6\x12\x00' (查看内容)
print(type(res)) # <class 'bytes'> (查看类型)
res2 = struct.unpack("i",res) # 使用什么 Format 打包就用什么解包
print(res2) # (1234566,) (是个元组)
print(type(res2)) # <class 'tuple'> (查看类型)
print(res2[0]) # 1234566
res = struct.pack("hiq",12,23,451312) # 传入多个值, 并使用不同的 Fromat
print(res) # b'\x0c\x00\x00\x00\x17\x00\x00\x00\xf0\xe2\x06\x00\x00\x00\x00\x00'
print(type(res)) # <class 'bytes'>
a,b,c = struct.unpack("hiq",res) # 使用解压赋值,有几个值就需要有几个 Fromat
print(a,b,c) # 12 23 451312