tcp/udp通信
tcp通信
服务端
import socket
soc = socket.socket()
soc.bind(('192.168.11.131',8080))
# soc.bind(('127.0.0.1',8084))
soc.listen(3)
conn, addr = soc.accept()
print(f'与{addr}连接成功')
data = conn.recv(1024)
print('有人向我发了',data.decode())
conn.send(data.upper())
print('我返回了',data.upper().decode())
conn.close()
soc.close()
客户端
import socket
soc = socket.socket()
soc.connect(('192.168.11.131',8080))
# soc.connect(('127.0.0.1',8084))
print("我发出的",'hello world')
soc.send('hello world'.encode())
data = soc.recv(1024)
print('服务端回复的:',data.decode())
soc.close()
解决tcp中的粘包问题
发数据时定制报头
import json
import struct
with open(file_path, 'rb') as f:
data = f.read()
headers = {'data_size': len(data), 'file_name': file_name}
len(data), 'file_name': file_name}
head_json = json.dumps(headers)
head_json_bytes = bytes(head_json, encoding='utf-8')
self.request.send(struct.pack('i', len(head_json_bytes)))
self.request.send(head_json_bytes)
self.request.send(data)
收数据时先收4字节,在收报头,最后收精准的数据
import json
import struct
head = client.recv(4)
head_json_len = struct.unpack('i', head)[0]
data = client.recv(head_json_len).decode('utf-8')
head_json = json.loads(data)
file_name = head_json['file_name']
file_len = head_json['data_size']
count = 0
data_file = b''
while count < file_len:
if file_len < 1024:
data = client.recv(file_len)
else:
if file_len - count >= 1024:
data = client.recv(1024)
else:
data = client.recv(file_len - count)
data_file += data
count += len(data)
# data_file 就是整个文件
udp通信
服务端
import socket
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8080))
while True:
data,addr = server.recvfrom(1024)
print(data.decode())
server.sendto(f'我收到了{data.decode()}'.encode('utf8'),addr)
server.close()
客户端
import socket
client = socket.socket(type=socket.SOCK_DGRAM)
while True:
client.sendto("老铁牛逼".encode('utf8'),('127.0.0.1',8080))
data,addr = client.recvfrom(1024)
print(data.decode())
client.close()