我正试图找到这两个数字的总和。 这些是我的服务器和客户端代码, 我想要的结果是客户收到:总和46 但我得到了 收到的客户:总和12 收到的客户:Sum 34
客户端:
# Echo client program
import socket
def parse_file(fName):
list = []
with open(fName) as f:
for line in 1f:
list.append(line.strip())
return list
HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# s.sendall('Hello, world')
# data = s.recv(1024)
# s.close()
# print 'Received', repr(data)
input_data = parse_file('foo')
for i in input_data:
s.sendall(str(i))
sum = s.recv(1024)
print "CLIENT RECEIVED : Sum ", sum
s.close()
服务器
import socket
def compute_sum(line):
result = sum(int(i) for i in line)
return result
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
print "SERVER RECIEVED : ", repr(data)
compute_sum(data)
conn.sendall(data)
conn.close()
和Foo包含
12
34
答案 0 :(得分:0)
您正在从文本文件中创建一个数字列表,但之后每次只发送(并因此求和)每个数字。您可以让服务器一次收集一个号码,然后然后将它们相加,或者一次性发送所有号码。我推荐后者。像这样:
<强>客户端强>
s.sendall(','.join(input_data))
sum = s.recv(1024)
服务器强>
def compute_sum(line):
return sum(int(i) for i in line.split(','))
这会将数字作为单个字符串一起发送到服务器,例如12,34
。然后,服务器将对该单个字符串中的值求和。