网络编程
OSI七层协议
应,表,会,传,网,数,物
socket编程
1.Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口
socket模块用法
Ⅰ. TCP服务端
s = socket(socket.AF_INET,socket.SOCKET_STREAM)
s.bind(("127.0.0.1",8080))
s.listen(5)
conn,addr = s.accept()
conn.recv(1024)
conn.send()
conn.close()
s.close()
Ⅱ. TCP客户端
c = socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect(("127.0.0.1",8080))
c.send("".encode("utf8")) # 只能发送字节类型
c.recv(1024)
c.close()
链接循环和通信循环
1. TCP客户端
s = socket(socket.AF_INET,socket.SOCKET_STREAM)
s.bind(("127.0.0.1",8080)
s.listen(5)
while True: # 链接循环
conn,addr = s.accept(5)
while True: # 通信循环
conn.recv(1024)
conn.send("".encode("utf8"))
conn.close()
s.close()
2. TCP服务端
c = socket(socket.AF_INET,socket.SOCKET_STREAM)
c.connect(("127.0.0.1",8080))
while True:
msg = input(">>:").strip()
if len(msg) == 0: continue
c.send(msg.encode("utf8"))
c.recv(1024)
c.close()
UDP服务端
s = socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("127.0.0.1",8080))
while True:
msg,addr = s.recvfrom(1024)
s.sendto(msg.upper(),addr)
UDP客户端
c = socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msg = input(">>:").strip()
if msg == 0: continue
c.sendto(msg.encode("utf8"),("127.0.0.1",8080))
back_msg,addr = c.recvfrom(1024)
粘包现象
1. TCP流式协议才会出现粘包现象
2. 如何解决粘包问题(这里用到一个模块,struct,可以把一个类型转成固定长度的bytes,并且可以反解)
import json,struct
header = {'file_size':1000000000,'file_name':'/d/movie/jap/youkonw.txt','md5':"5451254121"}
head_bytes = bytes(json.dumps(header),encoding='utf8')
head_len_bytes = struct.pack('i',len(head_bytes))
c.send(head_len_bytes)
c.send(head_bytes)
c.sendall()
import json,struct
head_len_bytes = conn.recv(4)
x = struct('i',head_len_bytes)[0]
head_bytes = conn.recv(x)
header = json.loads(head_bytes)
real_data_len = head["file_size"]
conn.recv(read_data_len)