【发布时间】:2019-10-26 20:45:17
【问题描述】:
我正在尝试使一个非常简单的客户端系统变得简单,但我不确定它有什么问题。它应该是一个计算器系统。这是客户端的代码:
import socket
IP = '127.0.0.1'
PORT = 8106
my_socket = socket.socket()
my_socket.connect((IP, PORT))
done = False
while not done:
command = raw_input("choose a command from [ADD, SUB, MUL, DIV, EXIT]")
command = command.upper()
my_socket.send(command)
data = my_socket.recv(20)
new_list = data.split(":")
if command in ["ADD", "SUB", "MUL", "DIV", "EXIT"]:
if command == "ADD":
print new_list[0] + "+" + new_list[1] + "=" + new_list[2]
if command == "SUB":
print new_list[0] + "-" + new_list[1] + "=" + new_list[2]
if command == "MUL":
print new_list[0] + "*" + new_list[1] + "=" + new_list[2]
if command == "DIV":
print new_list[0] + "/" + new_list[1] + "=" + new_list[2]
if command == "EXIT":
done = True
else:
print 'not valid'
这是服务器的代码:
import socket
import random
IP = '0.0.0.0'
PORT = 8106
server_socket = socket.socket()
server_socket.bind((IP, PORT))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
done = False
while not done:
message = client_socket.recv(4)
num1 = random.randint(-101, 100)
print num1
num2 = random.randint(-101, 100)
print num2
if message in ["ADD", "SUB", "MUL", "DIV", "EXIT"]:
if message == "ADD":
result = num1 + num2
elif message == "SUB":
result = num1 - num2
elif message == "MUL":
result = num1 * num2
elif message == "DIV":
result = float(num1) / float(num2)
elif message == "EXIT":
done = True
client_socket.send(str(num1) + ":" + str(num2) + ":" + str(result))
else:
client_socket.send("0:0:0")
现在,当我运行服务器,然后运行客户端,并多次选择“DIV”时,第一次也可以,但在第二次或第三次尝试时,我收到一条错误消息:
print new_list[0] + "/" + new_list[1] + "=" + new_list[2]
IndexError: list index out of range
我不确定为什么会这样。我试图打印“数据”来尝试解决它,有时数据只是一个数字,例如只有 46,而不是像 46:3:15.333 之类的东西
为什么会这样?
【问题讨论】:
标签: python python-2.7 server client client-server