Python入门学习-DAY32-链接循环与通信循环,粘包问题,远程控制,文件上传与下载
Posted LIFE
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python入门学习-DAY32-链接循环与通信循环,粘包问题,远程控制,文件上传与下载相关的知识,希望对你有一定的参考价值。
链接循环与通信循环
服务端
from socket import * IP = ‘127.0.0.1‘ PORT = 8181 ADDRESS = (IP, PORT) BUFSIZE = 1024 server = socket(AF_INET, SOCK_STREAM) server.bind(ADDRESS) server.listen(5) tag=True while tag: conn, addr = server.accept() while tag: try: data = conn.recv(BUFSIZE) if not data: print(‘服务端断开。。。‘) break print(‘>>>>‘,data.decode(‘utf-8‘)) conn.send(‘收到‘.encode(‘utf-8‘)) except ConnectionResetError: break conn.close() server.close()
客户端
import socket IP=‘127.0.0.1‘ PORT=8181 ADDRESS=(IP,PORT) BUFSIZE=1024 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(ADDRESS) while True: msg=input(‘>>>‘) if len(msg) == 0: continue client.send(msg.encode(‘utf-8‘)) data=client.recv(BUFSIZE) print(data.decode(‘utf-8‘)) client.close()
远程控制
服务端
import socket import subprocess IP = ‘192.168.13.126‘ PORT = 8282 ADDRESS = (IP, PORT) BUFSIZE = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDRESS) server.listen(5) tag=True while tag: conn, addr = server.accept() while tag: try: data = conn.recv(BUFSIZE) if not data: print(‘服务端断开。。。‘) break #获取sub对象 res = subprocess.Popen(data.decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(‘>>>>‘,data.decode(‘utf-8‘)) stdout=res.stdout.read() stderr=res.stderr.read() conn.send(stdout+stderr) except ConnectionResetError: break conn.close() server.close()
客户端
import socket IP=‘127.0.0.1‘ PORT=8282 ADDRESS=(IP,PORT) BUFSIZE=1024 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(ADDRESS) while True: msg=input(‘>>>‘) if len(msg) == 0: continue client.send(msg.encode(‘utf-8‘)) data=client.recv(BUFSIZE) print(data.decode(‘gbk‘)) client.close()
粘包问题
服务端
import socket import subprocess import struct import json IP = ‘127.0.0.1‘ PORT = 8383 ADDRESS = (IP, PORT) BUFSIZE = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDRESS) server.listen(5) tag = True while tag: conn, addr = server.accept() while tag: try: data = conn.recv(BUFSIZE) if not data: print(‘服务端断开。。。。‘) break # 获取sub对象 res = subprocess.Popen(data.decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(‘>>>>‘, data.decode(‘utf-8‘)) # 成功的结果 stdout = res.stdout.read() # 失败的结果 stderr = res.stderr.read() # 1.制作报头 header_dic = { ‘filename‘: ‘a.txt‘, ‘md5‘: ‘sd7a86d87sad6as‘, ‘total_size‘: len(stdout) + len(stderr) } header_json = json.dumps(header_dic) header_bytes = header_json.encode(‘utf-8‘) # 2.先发送报头长度 conn.send(struct.pack(‘i‘, len(header_bytes))) # 3.再发送报头 conn.send(header_bytes) # 4.最后发送数据 conn.send(stdout) conn.send(stderr) except ConnectionResetError: break conn.close() server.close()
客户端
import socket import struct import json IP = ‘127.0.0.1‘ PORT = 8383 ADDRESS = (IP, PORT) BUFSIZE = 1024 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDRESS) while True: msg = input(‘>>>‘) if len(msg) == 0: continue client.send(msg.encode(‘utf-8‘)) # 1.先获取报头长度 header_size = struct.unpack(‘i‘,client.recv(4))[0] #2.在获取报头 header_bytes=client.recv(header_size) header_json=header_bytes.decode(‘utf-8‘) header_dic=json.loads(header_json) print(header_json) total_size=header_dic[‘total_size‘] # 3.在获取真正数据 cmd_res=b‘‘ recv_size=0 while recv_size<total_size: data=client.recv(1024) recv_size+=len(data) cmd_res+=data print(cmd_res.decode(‘gbk‘)) client.close()
文件上传与下载
common
import json, struct, os def accept(type, obj): res = obj.recv(1).decode(‘utf-8‘) if res == ‘1‘: # 1.先获取报头长度 header_size = struct.unpack(‘i‘, obj.recv(4))[0] # 2.在获取报头 header_bytes = obj.recv(header_size) # 接受字节型的报头 header_json = header_bytes.decode(‘utf-8‘) # 将字节型的报头转化为原先的JSON格式 header_dic = json.loads(header_json) # 将JSON格式的报头转化为原先的字典 total_size = header_dic[‘total_size‘] print(header_dic) # 3.在获取真正数据 recv_size = 0 # 设置存放文件的路径 if type == ‘server‘: file_path = os.path.join(r‘C:UsersAdministratorDesktop服务端文件中心\%s‘ % header_dic[‘filename‘]) elif type == ‘client‘: file_path = os.path.join(r‘C:UsersAdministratorDesktop客户端文件中心\%s‘ % header_dic[‘filename‘]) # 判断文件内容是否为空 if total_size != 0: while (recv_size < total_size): data = obj.recv(10240) recv_size += len(data) with open(file_path, ‘wb‘) as f: f.write(data) else: f = open(file_path, ‘wb‘) f.close() return True else: return False def transfer(obj, filename): if os.path.exists(filename): obj.send(‘1‘.encode(‘utf-8‘)) filepath, tempfilename = os.path.split(filename) # 1.制作报头 header_dic = { ‘filename‘: tempfilename, ‘total_size‘: os.stat(filename).st_size } header_json = json.dumps(header_dic)#将字典格式序列化为json方便传送 header_bytes = header_json.encode(‘utf-8‘)#只能传送bytes类型,所以要转化为bytes类型 print(header_dic) # 2.先发送报头长度 obj.send(struct.pack(‘i‘, len(header_bytes))) # 3.再发送报头 obj.send(header_bytes) # 4.最后发送数据 with open(filename, ‘rb‘) as f: for i in f: obj.send(i) return True else: obj.send(‘0‘.encode(‘utf-8‘)) return False
服务端
import socket import common def run(): IP = ‘127.0.0.1‘ PORT = 8484 ADDRESS = (IP, PORT) BUFSIZE = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDRESS) server.listen(5) tag = True while tag: conn, addr = server.accept() while tag: try: data = conn.recv(BUFSIZE) if not data: print("客户端已断开。。。") break cmd, filename = data.decode("utf-8").split( ) print(‘>>>>‘, data.decode(‘utf-8‘)) if cmd==‘1‘: flag=common.accept(‘server‘,conn) if flag: print(‘接受成功‘) else: print(‘接受失败‘) elif cmd==‘2‘: flag=common.transfer(conn, filename) if flag: print(‘传送成功‘) else: print(‘传送失败‘) except ConnectionResetError: break conn.close() server.close() run()
客户端
import socket import common def run(): IP = ‘127.0.0.1‘ PORT = 8484 ADDRESS = (IP, PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDRESS) print(‘‘‘ 1.上传 2.下载 ‘‘‘) while True: msg = input(‘>>>(1/2):‘) if len(msg) == 0: continue if msg!=‘1‘ and msg!=‘2‘: print(‘指令错误‘) continue filename=input(‘文件地址:‘) client.send((msg+‘ ‘+filename).encode(‘utf-8‘)) if msg == ‘1‘: flag=common.transfer(client, filename) if flag: print(‘上传成功‘) else: print(‘上传失败‘) elif msg == ‘2‘: flag=common.accept(‘client‘,client) if flag: print(‘下载成功‘) else: print(‘下载失败‘) client.close() run()
以上是关于Python入门学习-DAY32-链接循环与通信循环,粘包问题,远程控制,文件上传与下载的主要内容,如果未能解决你的问题,请参考以下文章