设为首页 加入收藏

TOP

通过socket实现多个连接并实现ssh功能(二)
2017-10-22 06:06:41 】 浏览:451
Tags:通过 socket 实现 多个 连接 ssh 功能
port
struct import socket class FtpServer(object): def __init__(self, host, port): self.host = host self.port = port def ftp_server(self): # 声明协议类型 ftp_server = socket.socket() # 绑定本地网卡(多网卡选择),端口 ftp_server.bind((self.host, self.port)) # 监听端口 ftp_server.listen() # 监听 while True: print('等待...') conn, address = ftp_server.accept() while True: file_info = struct.calcsize('128sl') buf = conn.recv(file_info) if buf: file_name, file_size = struct.unpack('128sl', buf) # 使用strip()删除打包时附加的多余空字符 file_new_name = file_name.decode().strip('\00') print('start receiving...') fw = open(file_new_name, 'wb') received_size = 0 # 接收文件的大小 while not received_size == file_size: if file_size - received_size > 1024: r_data = conn.recv(1024) received_size += len(r_data) else: r_data = conn.recv(file_size - received_size) received_size = file_size fw.write(r_data) fw.close() if __name__ == '__main__': server = FtpServer('localhost', 8888) server.ftp_server() View Code

  客户端:

# -*- coding: UTF-8 -*-
import socket
import os
import struct


class FtpClient(object):
    # 定义一个FtpClien类

    def __init__(self, host, port):
        self.host = host
        self.port = port

    def client_push(self):

        # 声明协议类型,同时生成socket对象
        ftp_client = socket.socket()

        # 连接服务端
        ftp_client.connect((self.host, self.port))

        while True:
            # 切换文件目录路径
            print("输入文件目录路径")
            pwd = input(">>:").strip()

            # 列出文件名称
            files_list = os.listdir('{}'.format(pwd))
            for i in files_list:
                print(i)

            file_name = input('输入上传的文件名:').strip()
            file_path = os.path.join(pwd, file_name)
            if os.path.isfile(file_path):
                file_info = struct.calcsize('128sl')  # 定义打包规则
                f_head = struct.pack('128sl', file_name.encode('utf-8'), os.stat(file_path).st_size)
                ftp_client.send(f_head)
                fo = open(file_path, 'rb')
                while True:
                    file_data = fo.read(1024)
                    if not file_data:
                        break
                    ftp_client.send(file_data)
                fo.close()
                # 上传文件
                ftp_client.send(file_data)

# client.close()
if __name__ == '__main__':
    client = FtpClient('localhost', 8888)
    client.client_push()
View Code

  结果:

  

  在socket_server.py文件位置处能看到上传的文件

   

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇win10 + python3.6 + VSCode + te.. 下一篇logging模块小知识--同时往不同文..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目