如何通过TCP与Python发送后将字符串转换为浮点数?

时间:2018-05-10 13:17:39

标签: python string sockets tcp

我正在尝试使用带有Python的TCP套接字将连续温度数据从我的Raspberry Pi 3发送到PC。我不能发送浮点值,我以字符串格式发送连续的浮点值流,并希望将所有这些转换为浮点类型。

我收到这样的错误:

"ValueError: could not convert string to float '25.69'.

这是我的服务器代码(在raspberry pi上运行),我只包含了具体的部分:

def dataTransfer(conn):
    # A big loop that sends/receives data until told not to.
    while True:
    reply = GET_OBJ_TEMP()
    reply = str(reply)
    #conn.sendall(str.encode(reply)) # don't have to encode/decode, I think it's only for Python 3
    conn.sendall(reply)
    print("Data has been sent!")
    #conn.close()

s = setupServer()
conn = setupConnection()
dataTransfer(conn)

这是客户端代码(在PC上):

import socket

host = '10.0.0.94'
port = 5560

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

#while True:
#s.send(str.encode(command))
reply = s.recv(1024)
#print(reply.decode('utf-8'))
#reply2 = reply.decode('utf-8')
reply2 = (repr(reply))
reply2 = float(reply2)
print reply2
print type(reply2)

s.close()

有人可以帮我把这些值作为浮点数或帮我直接发送浮点数,我需要它们以便我可以使用温度作为阈值。

0 个答案:

没有答案