码迷,mamicode.com
首页 > 其他好文 > 详细

套接字练习2

时间:2020-04-22 10:04:00      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:forever   open   load   ack   bre   elf   send   服务   enc   

# 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(rE:\python之路\01 课程\week08-day02\03 课后作业\下载的图片.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(rE:\python之路\01 课程\week08-day02\03 课后作业\下载的图片.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(rE:\python之路\01 课程\week08-day02\05 下载区, 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

标签:forever   open   load   ack   bre   elf   send   服务   enc   

原文地址:https://www.cnblogs.com/caoyu080202201/p/12749543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!