python網絡編程實現TCP和UDP連接
阿新 • • 發佈:2018-05-07
socket python tcp udp 實現TCP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket # 創建一個socket: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立連接: s.connect((‘www.sina.com.cn‘, 80)) # 發送數據: s.send(b‘GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n‘) # 接收數據: buffer = [] while True: # 每次最多接收1k字節: d = s.recv(1024) if d: buffer.append(d) else: break data = b‘‘.join(buffer) # 關閉連接: s.close() header, html = data.split(b‘\r\n\r\n‘, 1) print(header.decode(‘utf-8‘)) # 把接收的數據寫入文件: with open(‘sina.html‘, ‘wb‘) as f: f.write(html)
實現UDP連接
服務端: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 綁定端口: s.bind((‘127.0.0.1‘, 9999)) print(‘Bind UDP on 9999...‘) while True: # 接收數據: data, addr = s.recvfrom(1024) print(‘Received from %s:%s.‘ % addr) reply = ‘Hello, %s!‘ % data.decode(‘utf-8‘) s.sendto(reply.encode(‘utf-8‘), addr) 客戶端: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for data in [b‘Michael‘, b‘Tracy‘, b‘Sarah‘]: # 發送數據: s.sendto(data, (‘127.0.0.1‘, 9999)) # 接收數據: print(s.recv(1024).decode(‘utf-8‘)) s.close()
python網絡編程實現TCP和UDP連接