请帮我优化这段代码。 import socket s = socket.socket() print("发送端创建成功") s.bind(('localhost', 8998)) s.listen(3) print("等待连接") # s.settimeout(15.0) c, addr = s.accept() print("ip地址和端口号", addr) ack_expected = "1" ack = "0" while True: frame = input("输入要发送的信息") c.send(bytes(frame, 'utf-8')) while ack_expected != ack: try: c.settimeout(10.0) ack = c.recv(1024).decode() while ack_expected != ack: print(frame, "ack值不正确,验证失败,信息重新发送!") c.send(bytes(frame, 'utf-8')) ack = c.recv(1024).decode() except socket.timeout: while ack_expected != ack: print(frame, "超时10s,信息将重新发送!!") break print("验证通过,信息成功传输") stop_connection = input("输入'yes'以关闭连接,输入'no'以继续传输数据") if stop_connection == "yes": print("连接已关闭") c.close() s.close() break if ack_expected == "0": ack_expected = "1" else: ack_expected = "0"
时间: 2024-01-28 13:05:50 浏览: 79
可以考虑以下几点来优化代码:
1. 使用with语句来管理socket连接,避免手动关闭连接时出现异常
2. 将重复的代码逻辑封装成函数,使代码更加简洁、易读
3. 使用异常处理机制来处理网络连接中的异常情况
下面是优化后的代码:
```python
import socket
def send_data(c, frame, ack_expected):
# 发送数据
c.send(bytes(frame, 'utf-8'))
ack = None
while ack_expected != ack:
try:
# 设置接收超时时间为10秒
c.settimeout(10.0)
# 接收ack
ack = c.recv(1024).decode()
if ack_expected != ack:
print(frame, "ack值不正确,验证失败,信息重新发送!")
# 重新发送数据
c.send(bytes(frame, 'utf-8'))
except socket.timeout:
print(frame, "超时10s,信息将重新发送!!")
# 重新发送数据
c.send(bytes(frame, 'utf-8'))
print("验证通过,信息成功传输")
with socket.socket() as s:
print("发送端创建成功")
s.bind(('localhost', 8998))
s.listen(3)
print("等待连接")
c, addr = s.accept()
print("ip地址和端口号", addr)
ack_expected = "1"
ack = "0"
while True:
frame = input("输入要发送的信息")
send_data(c, frame, ack_expected)
stop_connection = input("输入'yes'以关闭连接,输入'no'以继续传输数据")
if stop_connection == "yes":
print("连接已关闭")
c.close()
break
if ack_expected == "0":
ack_expected = "1"
else:
ack_expected = "0"
```
阅读全文