修改你发给我的代码,客户端还可以用cat命令打开服务端共享文件夹下的某文件
时间: 2024-03-11 21:50:25 浏览: 78
好的,以下是修改后的代码:
服务端:
```python
import socket
import os
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP和端口
server_socket.bind(('localhost', 8000))
# 监听端口
server_socket.listen()
# 获取共享文件夹路径
shared_folder_path = os.path.join(os.getcwd(), 'shared_folder')
print('Server is listening on port 8000...')
while True:
# 等待客户端连接
client_socket, address = server_socket.accept()
print(f'Client {address} connected.')
# 接收客户端请求的文件名
file_name = client_socket.recv(1024).decode()
# 拼接文件路径
file_path = os.path.join(shared_folder_path, file_name)
# 判断文件是否存在
if os.path.isfile(file_path):
# 发送文件大小
file_size = os.stat(file_path).st_size
client_socket.send(str(file_size).encode())
# 等待客户端确认
client_socket.recv(1024)
# 发送文件内容
with open(file_path, 'rb') as f:
data = f.read(1024)
while data:
client_socket.send(data)
data = f.read(1024)
print(f'{file_name} sent to {address}.')
else:
# 文件不存在则发送错误信息
client_socket.send('ERROR'.encode())
# 关闭客户端连接
client_socket.close()
```
客户端:
```python
import socket
import os
# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8000))
# 请求文件名
file_name = input('Enter the file name: ')
# 发送文件名
client_socket.send(file_name.encode())
# 接收文件大小
file_size = int(client_socket.recv(1024).decode())
# 确认接收文件大小
client_socket.send(b'OK')
# 接收文件内容并保存到本地
with open(os.path.basename(file_name), 'wb') as f:
received_size = 0
while received_size < file_size:
data = client_socket.recv(1024)
f.write(data)
received_size += len(data)
print(f'{os.path.basename(file_name)} received from server.')
# 关闭连接
client_socket.close()
```
客户端在接收到文件大小后,可以使用`cat`命令打开共享文件夹下的某文件,例如:
```bash
cat shared_folder/test.txt
```
这样就可以在客户端终端中查看该文件内容了。
阅读全文