如何使用python套接字通过连接发送api响应?

时间:2019-05-31 00:37:48

标签: python sockets server

我正在尝试让服务器等待客户端建立连接,从客户端获取数据,使用该数据发出api请求,然后将响应发送给客户端。除了将响应发送回客户端(客户端功能刚刚超时)之外,其他所有操作都正常。如果将conn.sendall(“ anythinghere”)放入while True循环内,则此方法有效,但显然不会返回我需要它返回的内容。将conn.sendall放置在循环之外会导致客户端超时。

服务器代码

conn, addr = s.accept()

print('Connected by', addr)
fragments = []
while True:
    chunk = conn.recv(4096)
    if not chunk:
        break
    fragments.append(chunk)

action = "".join(fragments)

URL = "http://172.31.55.211/" + action

print("making request")
r = requests.get(url = URL)
data = r.json()

conn.sendall(data['message'])

客户代码

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print(s)
    s.connect((HOST, PORT))
    s.sendall(b'hellocvs')
    data = s.recv(1024)

    print('Received', repr(data))

    return {
        'statusCode': 200,
        'body': json.dumps(str(data))
    }

1 个答案:

答案 0 :(得分:0)

Size of G by sys 56 asizeof 338079824 G created in 17.36 factorial of 4: start@Fri May 31 11:39:26 2019 factorial of 8: start@Fri May 31 11:39:53 2019 factorial of 12: start@Fri May 31 11:40:19 2019 factorial of 20: start@Fri May 31 11:40:44 2019 factorial of 16: start@Fri May 31 11:41:10 2019 Process finished with exit code 0 行,服务器代码将无法运行,因为action = "".join(fragments)fragments,因此您需要bytes not string才能加入字节