一、Socket
Socket Families(地址簇)
socket.
AF_UNIX unix本机进程间通信
socket.
AF_INET IPV4
socket.
AF_INET6 IPV6
Socket Types
socket.
SOCK_STREAM #for tcp
socket.
SOCK_DGRAM #for udp
socket.
SOCK_RAW #原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
socket.
SOCK_RDM #是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
socket.
SOCK_SEQPACKET #废弃了
Socket 方法
socket.
socket
(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) 必会
sk.bind(address) 必会
s.bind(address) 必会
将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。
sk.listen(backlog) 必会
开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。
backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
这个值不能无限大,因为要在内核中维护连接队列
sk.setblocking(bool) 必会
是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。
sk.accept() 必会
接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
接收TCP 客户的连接(阻塞式)等待连接的到来
sk.connect(address) 必会
连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
sk.connect_ex(address)
同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061
sk.close() 必会
关闭套接字
sk.recv(bufsize[,flag]) 必会
接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。
sk.recvfrom(bufsize[.flag])
与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。
sk.send(string[,flag]) 必会
将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。
sk.sendall(string[,flag]) 必会
将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。
内部通过递归调用send,将所有内容发送出去。
sk.sendto(string[,flag],address)
将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。
sk.settimeout(timeout) 必会
设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
sk.getpeername() 必会
返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
sk.getsockname()
返回套接字自己的地址。通常是一个元组(ipaddr,port)
sk.fileno()
套接字的文件描述符
socket.
sendfile
(file, offset=0, count=None)
发送文件 ,但目前多数情况下并无什么卵用。
基本Socket实例
服务端
import socket server = socket.socket() #获得socket实例 server.bind(("localhost",9998)) #绑定ip port server.listen() #开始监听 print("等待客户端的连接...") conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来... print("新连接:",addr ) data = conn.recv(1024) print("收到消息:",data) server.close()
客户端
import socket client = socket.socket() client.connect(("localhost",9998)) client.send(b"hey") client.close()
二、SocketServer
SocketServer 简介
SocketServer是对Socket的封装,SocketServer子类的继承关系如下
本机
class
socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate
=
True
)
class
socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate
=
True
)
UDP协议
class
socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate
=
True
)
TCP协议
class
socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate
=
True
实现了TCP多线程
class ThreadingTCPServer(ThreadingMixIn, TCPServer):pass
实现了UDP多线程
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
创建SocketServer的基本步骤
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): """ The request handler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def setup(self): """启动前执行""" pass def handle(self): """处理过程""" # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) def finish(self): """结束时执行""" pass if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
三、作业
要求:
- 用户加密认证 实现
- 允许同时多用户登录 实现
- 每个用户有自己的家目录 ,且只能访问自己的家目录 实现
- 对用户进行磁盘配额,每个用户的可用空间不同
- 允许用户在ftp server上随意切换目录 实现
- 允许用户查看当前目录下文件 实现
- 允许上传和下载文件,保证文件一致性 实现
- 文件传输过程中显示进度条
- 附加功能:支持文件的断点续传
服务端
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen import socketserver import json import hashlib import os current_path = os.getcwd() conf_path = os.path.join(os.path.dirname(current_path), "conf") data_path = os.path.join(os.path.dirname(current_path), "data") def create_user(username, password): user_info = { "username": username, "password": password, "home_path": os.path.join(data_path, username) } user_info_str = json.dumps(user_info) user_conf_path = os.path.join(conf_path, username) with open(user_conf_path, "w") as f: f.write(user_info_str) class MyTCPHandler(socketserver.BaseRequestHandler): def setup(self): pass def cmd_put(self, *args): """客户端发起put命令时的处理方法""" file_name = os.path.join(data_path, os.path.join(args[0]["path"], args[0]["name"])) # home + current + filename file_total_size = args[0]["size"] if os.path.isfile(file_name): # 如果文件存在 file_name = file_name + ".new" # 文件名后买你加“new” client_upload = 200 # 这里可以判断能否上传文件 if client_upload: self.request.sendall(str(client_upload).encode("utf8")) f = open(file_name, "wb") file_size = 0 file_md5 = hashlib.md5() while file_size < file_total_size: # 如果没有接收完就一直接收 rec_size = 1024 if file_total_size - file_size < 1024: # 判断是否是最后一次接收,如果是只接收最后一部分 rec_size = file_total_size - file_size tmp_data = self.request.recv(rec_size) # 接收数据,循环写入文件 file_md5.update(tmp_data) f.write(tmp_data) file_size += len(tmp_data) else: f.close() print("receive file done") end_dict = { "file_name": file_name, "file_md5": file_md5.hexdigest() } self.request.sendall(json.dumps(end_dict).encode("utf8")) def cmd_get(self, *args): """客户端发起get命令时的处理方法""" username = args[0]["name"] file_path = os.path.join(data_path, args[0]["path"]) if os.path.isfile(file_path): file_size = os.stat(file_path).st_size send_data = { "path": file_path, "size": file_size, "status": 200 } self.request.sendall(json.dumps(send_data).encode("utf8")) client_response = json.loads(self.request.recv(1024)) if client_response == 200: with open(file_path, "rb") as f: for block in f: self.request.sendall(block) print("send file done") else: print("send file error") else: send_data = { "path": file_path, "size": None, "status": 404 } self.request.sendall(json.dumps(send_data).encode("utf8")) def cmd_cd(self, *args): print(args) cd_path = args[0]["path"] username = args[0]["name"] if cd_path.startswith(username): # 如果客户端发送过来的path开头是用户名则正常,否则是没有权限的 full_path = os.path.join(data_path, cd_path) if os.path.isdir(full_path): # 如果目录存在 send_code = "200" print(full_path) else: send_code = "404" print(full_path) elif cd_path == "": send_code = "200" print("cd_path is None") else: send_code = "401" print(cd_path) self.request.sendall(send_code.encode("utf8")) """客户端发起cd命令时的处理方法""" pass def cmd_dir(self, *args): """客户端发起dir命令时的处理方法""" dir_path = args[0]["path"] username = args[0]["name"] if dir_path.startswith(username): # 判断是否是用户自己的家目录开头,否则就没有权限 full_path = os.path.join(data_path, dir_path) if not os.path.exists(full_path): # 判断目录是否存在 send_data = "file or directory not exists" else: file_list = os.listdir(full_path) send_data = "" for i in file_list: send_data += i + "\n" else: send_data = "Permission denied" self.request.sendall(send_data.encode("utf8")) def handle(self): print("ftp_server start") receive_data = self.request.recv(1024) auth_info = json.loads(receive_data) # 接收认证信息 if os.path.isfile(os.path.join(conf_path, auth_info["username"])): # 判断用户用户的配置文件是否存在 f = open(os.path.join(conf_path, auth_info["username"]), "r") # 读取用户配置文件 local_user_info = json.loads(f.read()) f.close() if local_user_info["password"] == auth_info["password"]: # 判断用户密码是否正确 self.request.sendall("200".encode("utf8")) while True: # 密码正确,进入交互 try: print("进入循环") receive_data = self.request.recv(1024) data_dict = json.loads(receive_data) cmd_str = "cmd_%s" % data_dict["action"] if hasattr(self, cmd_str): # 如果有这个命令,则执行 func = getattr(self, cmd_str) func(data_dict) else: # 否则返回错误 print(data_dict) continue # self.request.sendall(receive_data) except ConnectionResetError as e: # 客户端退出异常 print("user disconnect", e) break else: self.request.sendall("401".encode("utf8")) else: self.request.sendall("404".encode("utf8")) def finish(self): pass server = socketserver.ThreadingTCPServer(("localhost", 8888), MyTCPHandler) create_user("glen", "abc") # 创建用户 server.serve_forever()
客户端
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Glen import socket import json import hashlib import os current_path = os.getcwd() conf_path = os.path.join(os.path.dirname(current_path), "conf") data_path = os.path.join(os.path.dirname(current_path), "data") class FtpClient(object): """实例化""" def __init__(self, name, password, ip, port): self.path = name self.client = socket.socket() self.ip = ip self.port = port self.auth_info = { "username": name, "password": password } def interactive(self): """与服务器交互""" self.connect() # 连接并认证 while True: send_data = input(self.path + ">>") # 等待用户输入 if not send_data: continue cmd_str = "cmd_%s" % send_data.split()[0] if hasattr(self, cmd_str): # 调用命令 func = getattr(self, cmd_str) func(send_data) else: self.cmd_help() # self.client.sendall(send_data.encode("utf8")) # receive_data = self.client.recv(1024) # print(receive_data.decode("utf8")) def connect(self): """连接服务器并验证,如果验证失败则退出""" self.client.connect((self.ip, self.port)) self.client.sendall(json.dumps(self.auth_info).encode("utf8")) auth_response = self.client.recv(1024).decode("utf8") # 发送验证信息,等待回应 if auth_response == "200": print("authentication OK") else: print("authentication failure") exit(auth_response) # 认证失败,程序退出 def cmd_put(self, *args): """上传文件到服务器""" file_name = args[0].split()[1] file_size = os.stat(file_name).st_size data_dict = { "action": "put", "name": file_name, "size": file_size, "path": self.path } self.client.sendall(json.dumps(data_dict).encode("utf8")) # 发送文件大小给客户端 server_response = self.client.recv(1024).decode("utf8") # 接收客户端返回信息,判断是否可以上传 file_md5 = hashlib.md5() # 实例化MD5 if server_response == "200": print("start put file") f = open(file_name, 'rb') for block in f: file_md5.update(block) # 循环更新MD5 self.client.sendall(block) else: print("put failure") end_dict = json.loads(self.client.recv(1024)) # 服务器接收完毕后返回校验状态 if end_dict["file_md5"] == file_md5.hexdigest(): # 对比客户端和服务端的MD5 print("put function end") else: print("file checksum error") @staticmethod def cmd_help(): print(""" pwd dir cd path get file_name put file_name """) def cmd_get(self, *args): """下载文件""" if len(args[0].split()) > 1: cmd_path = args[0].split()[1] if cmd_path.startswith("/"): get_path = cmd_path.lstrip("/") else: get_path = os.path.join(self.path, cmd_path) data_dict = { "action": "get", "name": self.auth_info["username"], "path": get_path } self.client.sendall(json.dumps(data_dict).encode("utf8")) server_response = json.loads(self.client.recv(1024)) file_total_size = server_response["size"] file_name = os.path.basename(server_response["path"]) get_status = server_response["status"] if get_status == 200: self.client.sendall("200".encode("utf8")) f = open(file_name, "wb") file_size = 0 while file_size < file_total_size: rec_size = 1024 if file_total_size - file_size < 1024: rec_size = file_total_size - file_size tmp_data = self.client.recv(rec_size) file_size += len(tmp_data) f.write(tmp_data) else: f.close() print("file receive done") elif get_status == 404: print(get_status) print("file not exist") else: print("get file error") else: print("please enter filename") def cmd_dir(self, *args): """查看目录文件列表""" if len(args[0].split()) > 1: cmd_path = args[0].split()[1] if cmd_path == "/": dir_path = self.auth_info["username"] elif cmd_path.startswith("/"): dir_path = cmd_path.lstrip("/") else: dir_path = os.path.join(self.path, cmd_path) else: dir_path = self.path data_dict = { "action": "dir", "path": dir_path, "name": self.auth_info["username"] } self.client.sendall(json.dumps(data_dict).encode("utf8")) server_response = self.client.recv(1024).decode("utf8") print(server_response) def cmd_cd(self, *args): """改变目录""" if len(args[0].split()) > 1: # 判断命令是否完整 cmd_path = args[0].split()[1] else: cmd_path = "" if cmd_path == "/": # 如果切换目录为根,则直接为用户名 cd_path = self.auth_info["username"] elif cmd_path == "" or cmd_path == ".": cd_path = self.path elif cmd_path == "..": if os.path.dirname(self.path): # 判断是否已经在目录底层 cd_path = os.path.dirname(self.path) else: cd_path = self.path elif cmd_path.startswith("/"): # 如果是以斜杠开头,则去掉斜杠 cd_path = cmd_path.lstrip("/") # 如果是以“/”开头的 else: cd_path = os.path.join(self.path, cmd_path) # 当前目录 + 要切换的目录 data_dict = { "action": "cd", "name": self.auth_info["username"], "path": cd_path } self.client.sendall(json.dumps(data_dict).encode("utf8")) server_response = self.client.recv(1024).decode("utf8") if server_response == "200": # 服务端检测,如果存在这个目录则切换则切换 self.path = cd_path print("change directory success") else: print("change directory failure") print(server_response) def cmd_pwd(self, *args): """查看当前目录""" # print(args) # data_dict = { # "action": "pwd", # "current_path": self.path # } # self.client.sendall(json.dumps(data_dict).encode("utf8")) # 发送client当前目录信息 # server_response = self.client.recv(1024) print(self.path) # 目录本地保存处理,服务器端验证即可,每个data_dict都上传目录 client = FtpClient("glen", "abc", "localhost", 8888) client.interactive()