python 网络编程
python网络编程常用模块及固定写法
socket模块
基于TCP的C/S架构
通信循环与连接循环
# 服务端
import socket
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 设置端口可重用
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# 设置阻塞
s.setblocking(1)
server.bind(('127.0.0.1',8080))
server.listen(5)
while True : # 循环连接客户端
conn, client_addr = server.accept()
print(client_addr)
while True:
try:
from_client_data = conn.recv(1024)
print(from_client_data.decode('utf-8'))
conn.send(from_client_data + b'SB')
except ConnectionResetError: # 客户端异常关闭
break
except ConnectionAbortedError:# 客户端主动断开连接
break
conn.close()
# server.close()
# 客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8080)) # 与服务端建立连接
while True:
client_data = input('>>>')
if client_data == 'quit':
break
client.send(client_data.encode('utf-8'))
from_server_data = client.recv(1024)
print(from_server_data.decode('utf-8'))
client.close()
recv工作方式
Receive up to buffersize bytes from the socket.
(最大从套接字接收缓冲区中接收缓冲区大小的字节串.)
For the optional flags argument, see the Unix manual.(可选参数的设置参口Unix手册.)
When no data is available, block untilat least one byte is available or until the remote end is closed.
(当缓冲没有数据是,该方法阻塞,直到缓冲区中出现至少一个数据或者远程端的连接正常关闭.)
When the remote end is closed and all data is read, return the empty string.
(当远程端正常关闭,且缓冲区中数据被取完时,该函数返回空值.)
远程控制
socketserver模块
并发服务器固定写法
import socketserver # 引入模块
class MyServer(socketserver.BaseRequestHandler):
# 类名随便定义,但是必须继承socketserver.BaseRequestHandler此类
def handle(self): # 写一个handle方法,固定名字
while True:
# self.request 相当于conn管道
from_client_data = self.request.recv(1024).decode('utf-8')
print(from_client_data)
to_client_data = input('服务端回信息:').strip()
self.request.send(to_client_data.encode('utf-8'))
if __name__ == '__main__':
ip_port = ('127.0.0.1', 8080)
socketserver.TCPServer.allow_reuse_address = True # 允许端口重用
server = socketserver.ThreadingTCPServer(ip_port, MyServer)
# 对 socketserver.ThreadingTCPServer 类实例化对象,将ip地址,端口号以及自己定义的类名传入,并返回一个对象
server.serve_forever() # 对象执行serve_forever方法,开启服务端