【Python网络编程】UDP聊天、TCP文件下载、多线程UDP聊天器、多进程拷贝文件

一、UDP聊天

客户端

import socket
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定地址
server_addr = ("",8080)
udp_socket.bind(server_addr)
for x in range(100):
   #打印接收的内容
   recv_content,recv_addr = udp_socket.recvfrom(1024)
   print("%s:%s"%(recv_addr,(recv_content.decode("utf-8"))))

服务器

import socket

#创建套间字
udp_broadcast = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

udp_broadcast.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)

for x in range(100):
   #发送消息
   send_content = input("发送的广播内容:")
   udp_broadcast.sendto(send_content.encode("utf-8"), ("<broadcast>", 8080))
udp_broadcast.close()

二、TCP文件下载

服务器

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',8059))
s.listen(5)
while True:
    conn,add = s.accept()
    print(add)
    while True:
        data = conn.recv(1024)
        file_name = data.decode('utf-8')
        print("客户端打印的文件名称为:",file_name)
        try :
            with open("./"+file_name,"rb") as f:
                file_date  = f.read()
        except:
            print("服务器没有该文件:",file_name)
        if(file_date):
            print("服务器存在该文件")
            conn.send(file_date)
            file_date = ""

客户端

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1',8059))
while True:
    send_data = input("请输入要下载文件名称")
    s.send(send_data.encode('utf-8'))
    recvdata = s.recv(1024)
    if(recvdata):
        print("存在该文件并已经下载")
        with open(send_data,"wb") as f:
            f.write(recvdata)
    else:
        print("不存在该文件")

三、多线程UDP聊天

服务器

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',9527))
while True:
    data,add = s.recvfrom(1024)
    print("Message:",data.decode('utf-8'),"From Address:",add)
    send_data = input("服务器发送数据:")
    s.sendto(send_data.encode('utf-8'),add)

客户端

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print("Client is running")

def sendData():
    send_data = input("发送数据:")
    s.sendto(send_data.encode('utf-8'), ('127.0.0.1', 9527))

def recvData():
    data,add = s.recvfrom(1024)
    print("Message:", data.decode('utf-8'), "From Address:", add)


while True:
   choose = input("请选择发送或接受数据(1表示发送数据,其他表示接收数据):")
   if(choose == '1'):
       sendData()
   else:
       recvData()

四、多进程拷贝文件

```javascript
import threading
import os
import shutil
import multiprocessing
import time

# 创建拷贝任务
def copy_work(q,source_dir, dest_dir, file_name):
    # 拼接文件名路径
    source_file_path = source_dir + '/' + file_name
    dest_file_path = dest_dir + '/' + file_name
    # 打开目标文件
    with open(dest_file_path, 'wb') as dest_file:
        # 打开源文件
        with open(source_file_path, 'rb') as source_file:
            # 写入数据
            while True:
                source_file_data = source_file.read(1024)
                if source_file_data:
                    dest_file.write(source_file_data)
                else:
                    break
    # 当结束该文件复制时,把该文件名放入q的消息队列
    q.put(file_name)

if __name__ == '__main__':
    # 指定源目录和目标目录
    source_dir = input("输入源目录:")
    dest_dir = input("输入目标目录")
    if os.path.exists(source_dir):
        if os.path.exists(dest_dir):
            # shutil.rmtree(dest_dir)
            print("目标文件夹已存在,如果目录内存在同名文件,将覆盖")
        else:
            # 创建目标文件夹
            os.mkdir(dest_dir)
        # 获取源目录文件列表
        source_file_list = os.listdir(source_dir)
        print(source_file_list)
        # 创建消息队列用于进程间通信,主要用于显示已经完成的进程,来实现复制文件夹的进度
        q = multiprocessing.Queue()
        for file_name in source_file_list:
            copy_thread = multiprocessing.Process(target=copy_work, args=(q,source_dir, dest_dir, file_name))
            copy_thread.start()
        # 判断拷贝百分比
        all_file_num = len(source_file_list)  # 计算所有文件个数
        copy_ok = 0
        while True:
            file_name = q.get()
            # print("已经完成copy: %s" % file_name)
            copy_ok += 1
            # time.sleep(0.1)
            print("\r拷贝的进度为:%.2f %%" % (copy_ok * 100 / all_file_num), end="")

            if copy_ok >= all_file_num:
                break
    else:
        print("请确认源目录是否存在或者是否拼写错误")


posted @ 2021-01-13 09:39  嗨Sirius  阅读(128)  评论(0编辑  收藏  举报