如何从字符串

时间:2017-02-18 04:19:31

标签: python sockets server client

我正试图找到这两个数字的总和。这些是我的服务器和客户端代码,我想要的结果是

收到的客户:Sum 46

但我得到了

客户收到:总和12

收到客户:Sum 34

客户端:

    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))

   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

23
12

1 个答案:

答案 0 :(得分:1)

你的print语句在你的循环中,并且sum每次都被设置为新值,而不是增加适当的量。试试这个:

sum = 0

for i in input_data:
    s.sendall(str(i))
    sum += int(s.recv(1024))

print "CLIENT RECEIVED : Sum ", sum