Python打卡第八周

Posted yuanjun93

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python打卡第八周相关的知识,希望对你有一定的参考价值。

socket函数编程

 

客户端

import socket,time
import os
server = socket.socket()
server.bind((localhost,9999))
server.listen()

while True:
    conn,addr = server.accept()
    print("the new :" ,addr)
    while True:
        data = conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
        print("执行指令:",data)
        cmd_res = os.popen(data.decode()).read()
        print("before send",len(cmd_res))
        if len(cmd_res) == 0:
            cmd_res = "cmd has no output"
        conn.send( str(len(cmd_res.encode())).encode("utf-8") )
        #time.sleep(0.5)#避免粘包
        client_ack = conn.recv(1024)#wait client to confirm
        conn.send(cmd_res.encode("utf-8"))
        print("send done")

 

服务端

import socket

client = socket.socket()

client.connect((localhost,9999))

while True:
    cmd = input(">>:").strip()
    if len(cmd) == 0:
        continue
    client.send(cmd.encode("utf-8"))
    cmd_res_size = client.recv(1024)
    print("命令结果大小:",cmd_res_size)
    client.send("准备好接受了".encode("utf-8"))
    received_size = 0
    received_data = b‘‘
    while received_size < int(cmd_res_size.decode()):
        data = client.recv(1024)
        received_size += len(data)
        # print(data.decode())
        # print(received_size)
        received_data += data
    else:
        print("cmd res receive done...",received_size)
    # cmd_res = client.recv(1024)
        print(cmd_res.decode())

server.close()

 

并发客户端

import socket,time,hashlib
import os
server = socket.socket()
server.bind((localhost,9999))
server.listen()

while True:
    conn,addr = server.accept()
    print("the new :" ,addr)
    while True:
        data = conn.recv(1024)
        if not data:
            print("客户端已断开")
            break

        cmd,filename = data.decode().split()
        print(fliename)
        if os.path.isfile(filename):
            f = open(filename,"rb")
            m = hashlib.md5()
            file_size = os.stat(filename).st_size
            conn.send(str(file_size).encode())#send file size
            conn.recv(1024)#wait for ack
            for line in f:
                #m.updata(line)
                conn.send(line)

            #print("file md5 ",m.hexdigest())
            f.close()
            conn.send(m.hexdigest().encode())#send md5
        print("send done")

server.close()

 

并发服务端

import socket
import hashlib
client = socket.socket()

client.connect((localhost,9999))

while True:
    cmd = input(">>:").strip()
    if len(cmd) == 0:
        continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response = client.recv(1024)
        print("server response:",server_response)
        client.send(b"ready to recv file")
        file_total_size = int(server_response.decode())
        received_size = 0
        filename = cmd.split()[1]
        f = open(filename + ".new","wb")
        m = hashlib.md5()
        while received_size <file_total_size:
            data =client.recv(1024)
            recevied_size += len(data)
            m.updata(data)
            f.write(data)
            #print(flie_total_size,received_size)
        else:
            new_file_md5 = m.hexdigest()
            print("file recv done",received_size,file_total_size)
            f.close()
        server_file_md5 = client.recv(1024)
        print("server file md5:",server_file_md5)
        print("client file md5:",new_file_md5)
server.close()

 

基本服务端

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 handle(self):
        # self.request is the TCP socket connected to the client
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print(" wrote:".format(self.client_address[0]))
                print(self.data)
                # if not self.data:#客户端断了
                #     print(self.client_address,"断开了")
                #     break
                # just send back the same data, but upper-cased
                self.request.sendall(self.data.upper())
            except ConnectionResetError as e:
                print("err",e)
                break

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

 

 

FTP上传client

import socket
import hashlib
import os
import json

class FtpClient(object):

    def __init__(self):
        self.client = socket.socket()

    def help(self):
        msg = ‘‘‘
        ls
        pwd
        cd ../..
        get filename
        put filename
        ‘‘‘
    def connect(self,ip,port):
        self.client.connect((ip,port))

    def interactive(self):
        #self.authenticate()
        while True:
            cmd = input(">>")
            if len(cmd) == 0:
                continue
            cmd_str = cmd.split()[0]
            if hasattr(self,"cmd_%s"%cmd_str):
                func = getattr(self,"cmd_%s"%cmd_str)
                func(cmd)
            else:
                self.help()
    def cmd_put(self,*args):
        cmd_split = args[0].split()
        if len(cmd_split) > 1:
            filename = cmd_split[1]
            if os.path.isfile(filename):
                filesize = os.stat(filename).st_size
                msg_dic =
                    "action":"put",
                    "filename":filename,
                    "size":filesize,
                    "overriden":True
                
                self.client.send(json.dumps(msg_dic).encode("utf-8"))
                print("send",json.dumps(msg_dic).encode("utf-8"))
                #防止粘包,等服务器确认
                server_response = self.client.recv(1024)
                f = open(filename,"rb")
                for line in f:
                    self.client.send(line)
                else:
                    print("file upload success...")
                    f.close()
            else:
                print(filename,"is not exist")

    def cmd_get(self):
        pass

ftp = FtpClient()
ftp.connect("localhost",9999)
ftp.interactive()

 

FTP上传server

import socketserver
import json
import os
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 put(self,*args):
        ‘‘‘接受客户端文件‘‘‘
        cmd_dic = args[0]
        filename = cmd_dic["filename"]
        filesize = cmd_dic["size"]
        if os.path.isfile(filename):
            f = open(filename+".new","wb")
        else:
            f = open(filename,"wb")

        self.request.send(b"200 ok")
        received_size = 0
        while received_size < filesize:
            data = self.request.recv(1024)
            f.write(data)
            received_size += len(data)
        else:
            print("file [%s] has uploaded.."%filename)

    def handle(self):
        # self.request is the TCP socket connected to the client
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print(" wrote:".format(self.client_address[0]))
                print(self.data)
                cmd_dic = json.loads(self.data.decode())
                action = cmd_dic["action"]
                if hasattr(self,action):
                    func = getattr(self,action)
                    func(cmd_dic)
                # if not self.data:#客户端断了
                #     print(self.client_address,"断开了")
                #     break
                # just send back the same data, but upper-cased
                self.request.sendall(self.data.upper())
            except ConnectionResetError as e:
                print("err",e)
                break

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

 

以上是关于Python打卡第八周的主要内容,如果未能解决你的问题,请参考以下文章

ARTS打卡第八周

学号:201521123116 《java程序设计》第八周学习总结

第八周总结

Python学习笔记——进阶篇第八周———异常处理

广东海洋大学 电子1151 孔yanfei python语言程序设计 第八周

广东海洋大学 电子1151 孔yanfei python语言程序设计 第八周