Python 网络编程
1. 基于socket网络编程
服务端代码:
import socket # 创建一个socket对象 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定IP地址(或主机名)和端口号 s.bind(('127.0.0.1', 8080)) # 监听端口 s.listen() while True: # 阻塞程序,等待客户端连接 conn, address = s.accept() print(address) # 接收客户端数据 data = conn.recv(1024) print(data.decode()) # 向客户端发送数据 conn.send('This is server.'.encode()) conn.close() s.close()
客户端代码:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接服务器 s.connect(('127.0.0.1', 8080)) s.send('Who are you?'.encode()) data = s.recv(1024) print(data.decode()) s.close()
2. 基于URL网络编程
import urllib.request import urllib.parse url = 'https://www.baidu.com/s' # HTTP请求参数,字典对象 params_dict = {'ie':'utf-8', 'f':8, 'rsv_bp':1, 'tn':'baidu', 'wd':163} # 将字典转换为字符串 params_str = urllib.parse.urlencode(params_dict) # 组装请求URL url = url + '?' + params_str print(url) # 创建Request对象,data参数没有指定则是GET请求,否则是POST请求 req = urllib.request.Request(url) # 发送HTTP请求 with urllib.request.urlopen(req) as response: data = response.read() json_data = data.decode() print(json_data)