Python: Simulate the client to send a file download request to the server

Requirements: Enter the file name on the client, and send the file name to the server via the client. The server returns the content of the file to the client, simulating the work content of the client sending a file download request to the server

The first preparations that need to be done are as follows:
Environmental preparation

  • Two computers under the same network segment (both are required to be equipped with a python environment), the same network segment can be understood as two computers accessing the same wifi
  • If there is only one computer, you can set up a virtual machine for simulation (requires a python environment)

Confirm the ip address of one of the computers and use it as the server.
I am a mac, and the confirmation content is as follows
Insert picture description here

I have exactly two computers in my hand, so I use one as the server and the other as the client, and write the following code

server side

import socket,os

# 创建一个基于tcp的socket连接
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# 绑定ip地址和端口号
s.bind(('192.168.1.104',9000))

# 监听
s.listen(128)

# 接受客户端发来的请求
client_socket,client_addr = s.accept()
data = client_socket.recv(1024).decode('utf8')

# 读取文件,返回给客户端
if os.path.isfile(data):
    print('读取文件,将文件内容返回给客户端')
    with open(data,'r',encoding = 'utf8') as file:
        content = file.read()
        client_socket.send(content.encode('utf8'))
else:
    print('文件不存在')

# 关闭socket
s.close()

client side

import socket

# 创建一个基于tcp的socket连接
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# 连接服务ip地址及端口号
s.connect(('192.168.1.104',9000))

# 向服务端发送数据
file_name = input('PLEASE INPUT FILE NAME:')
s.send(file_name.encode('utf8'))

# 接受服务端返回的文件内容,并写入到文件
content = s.recv(1024).decode('utf8')
with open(file_name,'w',encoding='utf8') as file:
    file.write(content)

# 关闭socket
s.close()

Guess you like

Origin blog.csdn.net/weixin_42161670/article/details/114603900