Ai
1 Star 0 Fork 0

cf2006/Python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server1.py 2.10 KB
一键复制 编辑 原始数据 按行查看 历史
cf2006 提交于 2025-04-16 20:48 +08:00 . 提交说明
import socket
import os
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('192.168.146.120', 1234)
server_socket.bind(server_address)
# 监听连接
server_socket.listen(1)
print('服务器正在监听 {}:{}'.format(*server_address))
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('接受来自 {} 的连接'.format(client_address))
while True:
# 接收客户端消息
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
print('客户端说: {}'.format(data))
# 检测是否是文件操作指令
if data.lower().startswith("file:"):
# 提取文件操作指令
file_command = data.split(":")[1].strip()
if file_command.startswith("read"):
# 读取文件
file_path = file_command.split()[1]
try:
with open(file_path, 'r', encoding='utf-8') as file:
file_content = file.read()
response = f"文件内容:\n{file_content}"
except FileNotFoundError:
response = "文件未找到!"
except Exception as e:
response = f"读取文件时发生错误:{e}"
elif file_command.startswith("write"):
# 写入文件
file_path, content = file_command.split()[1], " ".join(file_command.split()[2:])
try:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
response = "文件写入成功!"
except Exception as e:
response = f"写入文件时发生错误:{e}"
else:
response = "未知的文件操作指令!"
client_socket.send(response.encode('utf-8'))
else:
# 普通消息交互
message = input('请输入要发送给客户端的消息: ')
client_socket.send(message.encode('utf-8'))
if input("是否要继续?Y/N") == "N":
break
# 关闭连接
client_socket.close()
server_socket.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/cf2006/python.git
git@gitee.com:cf2006/python.git
cf2006
python
Python
master

搜索帮助