从服务器检索数据并处理计算

问题描述 投票:0回答:1

我的代码应该使用套接字模块连接到端口 2000 上的 37.59.31.202 服务器。然后我需要发送服务器通过连接发送的 100 次计算的结果。我相当粗糙的代码应该可以工作,但是当我尝试向服务器发送响应时,最后出现错误,并且必须对字符串“结果”进行编码才能正确发送。

import socket
import time

ip_address = "37.59.31.202"
port = 2000

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((ip_address, port))
    print("\nconnected")
    time.sleep(1)

    response = s.recv(1024)
    print(response.decode("utf-8"))
    print("\nresponse received")
    time.sleep(1)

    a = input()

    s.sendall(b"1\n")

    for i in range(100):
        response = s.recv(1024)
        rep = response.decode("utf-8")
        print(rep)

        a = input()
        response = s.recv(1024)
        rep = response.decode("utf-8")
        print(rep)

        calcul=""

        for x in rep:
            if x.isdigit():
                calcul += x
            elif x in ("-", "+", "/", "*"):
                calcul += x            

        result = eval(calcul)
        result = str(result)
        s.sendall(b""+result.encode(encoding="ascii")+"\n")
        print("response %s sent" % result)
        time.sleep(1)

我在互联网上没有找到任何对我的案例有价值的东西,这就是我在这里问的原因。预先感谢您的帮助。

python sockets server encode
1个回答
0
投票

问题是用 utf-8 而不是 ascii 对结果进行编码,并且不写 ' ' 表达式之后。祝大家有美好的一天,谢谢

© www.soinside.com 2019 - 2024. All rights reserved.