代码拉取完成,页面将自动刷新
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()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。