Python網路程式設計實現TCP和UDP連線, 使用socket模組, 所有程式碼在python3下測試透過。
實現TCP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket # 建立一個socket: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立連線: s.connect(('www.baidu.com', 80)) # 傳送資料: s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\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()