BZ易风

导航

 

服务器端

 1 import socket
 2 
 3 
 4 def send_file_2_client(new_client_socket,client_addr):
 5     # 接收信息
 6     file_name = new_client_socket.recv(1024).decode("utf-8")
 7 
 8     print("客户%s要下载的文件是:%s" % (str(client_addr), file_name))
 9 
10     # 定义发送的内容
11     send_content = None
12 
13     # 打开文件
14     try:
15         f = open(file_name,"rb")
16         send_content = f.read()
17         f.close()
18     except Exception as ret:
19         print("没有该文件信息")
20 
21     # 不做判断 如果没有该文件会报错:TypeError: a bytes-like object is required, not 'NoneType'
22     if send_content:
23         new_client_socket.send(send_content)
24 
25 
26 def main():
27     # 创建套接字
28     tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
29 
30     # 绑定端口
31     tcp_server_socket.bind(("",7788))
32 
33     # 被动监听
34     tcp_server_socket.listen(128)
35 
36     while True:
37         # 接收客户端信息
38         new_client_socket,client_addr = tcp_server_socket.accept()
39 
40         # while True:
41         send_file_2_client(new_client_socket,client_addr)
42 
43 
44         # 关闭
45         new_client_socket.close()
46     # 关闭套接字
47     tcp_server_socket.close()

客户端

import socket


def main():
    # 创建
    tcp_client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    # 连接服务器
    # ip和port可以写死 也可以用input() 输入
    server_ip = input("请输入服务器IP:")
    server_port = int(input("请输入端口:"))
    tcp_client_socket.connect((server_ip,server_port))

    # 发送信息
    file_name = input("请输入要下载的文件名:")
    tcp_client_socket.send(file_name.encode("utf-8"))

    # 接收对方发来的数据
    recv_data = tcp_client_socket.recv(1024)
    print(recv_data)
    if recv_data:
        with open("[接收]" + file_name,"wb") as f:
            f.write(recv_data)

    # 关闭套接字
    tcp_client_socket.close()

 

posted on 2019-08-19 16:13  BZ易风  阅读(458)  评论(0编辑  收藏  举报