python网络编程自学_五分钟搞定Python网络编程实现TCP和UDP连接
Python網(wǎng)絡(luò)編程實(shí)現(xiàn)TCP和UDP連接, 使用socket模塊, 所有代碼在python3下測(cè)試通過(guò)。
實(shí)現(xiàn)TCP#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
# 創(chuàng)建一個(gè)socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立連接:
s.connect(('www.baidu.com', 80))
# 發(fā)送數(shù)據(jù):
s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n')
# 接收數(shù)據(jù):
buffer = []
while True:
# 每次最多接收1k字節(jié):
d = s.recv(1024)
if d:
buffer.append(d)
else:
break
data = b''.join(buffer)
# 關(guān)閉連接:
s.close()
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
# 把接收的數(shù)據(jù)寫(xiě)入文件:
with open('sina.html', 'wb') as f:
f.write(html)
實(shí)現(xiàn)UDP連接
服務(wù)端:#!/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:
# 接收數(shù)據(jù):
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']:
# 發(fā)送數(shù)據(jù):
s.sendto(data, ('127.0.0.1', 9999))
# 接收數(shù)據(jù):
print(s.recv(1024).decode('utf-8'))
s.close()
總結(jié)
以上是生活随笔為你收集整理的python网络编程自学_五分钟搞定Python网络编程实现TCP和UDP连接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 雷军:小米才12岁 研发投入几乎超过所有
- 下一篇: python创建变量并赋值_python