套接字练习2
Posted caoyu080202201
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了套接字练习2相关的知识,希望对你有一定的参考价值。
# tcp服务端 import socketserver import os import json import struct class MyRequestHandle(socketserver.BaseRequestHandler): def handle(self): while 1: try: recv_data = self.request.recv(1024) if len(recv_data) == 0: break if recv_data.decode(‘utf-8‘) == ‘下载‘: data_size = os.path.getsize(r‘E:python之路 1 课程week08-day02 3 课后作业下载的图片.jpg‘) head_dict = {‘data_size‘: data_size} head_dict_json = json.dumps(head_dict) head_dict_bytes = head_dict_json.encode(‘utf-8‘) tag_4 = struct.pack(‘i‘, len(head_dict_bytes)) self.request.send(tag_4) self.request.send(head_dict_bytes) with open(r‘E:python之路 1 课程week08-day02 3 课后作业下载的图片.jpg‘, ‘rb‘)as f: for line in f: self.request.send(line) except Exception as e: print(e) break self.request.close() s = socketserver.ThreadingTCPServer((‘127.0.0.1‘, 3001), MyRequestHandle) s.serve_forever()
# tcp客户端 import socket import os import json import struct client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((‘127.0.0.1‘, 3001)) while 1: send_data = input(‘上传or下载:‘).strip() if len(send_data) == 0: continue client.send(send_data.encode(‘utf-8‘)) if send_data == ‘下载‘: tag_4 = client.recv(4) head_dict_len = struct.unpack(‘i‘, tag_4)[0] head_dict_bytes = client.recv(head_dict_len) head_dict_json = head_dict_bytes.decode(‘utf-8‘) head_dict = json.loads(head_dict_json) data_size = head_dict.get(‘data_size‘) recv_size = 0 file_path = os.path.join(r‘E:python之路 1 课程week08-day02 5 下载区‘, r‘下载的图片.jpg‘) with open(r‘{}‘.format(file_path), ‘wb‘)as f: while recv_size < data_size: recv_data = client.recv(1024) f.write(recv_data) recv_size += len(recv_data)
以上是关于套接字练习2的主要内容,如果未能解决你的问题,请参考以下文章
spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段
Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段