【发布时间】:2018-05-23 18:15:52
【问题描述】:
我正在测试一个简单的客户端/服务器套接字设置。从客户端发送字符串值=> 服务器很容易使用:
bytes(my_string, "UTF-8")
但是,现在我正在尝试发送一个数字数组(一些浮点数),我收到了这个错误:
Traceback (most recent call last):
File "client.py", line 26, in <module>
main2()
File "client.py", line 22, in main2
s.send(bytes(sample))
TypeError: 'float' object cannot be interpreted as an integer
假设我必须发送字节,将浮点数转换为字节然后在收到后返回浮点数的最佳方法是什么?
这是客户端代码:
def main2():
import socket
s = socket.socket()
host = socket.gethostname() # client and server are on same network
port = 1247
s.connect((host, port))
print(s.recv(1024))
sample = [0.9,120000,0.85,12.8,0.1,28,16,124565,0.72,3.9]
s.send(bytes(sample))
print("the message has been sent")
if __name__ == '__main__':
main2()
还有服务器代码,以防万一:
def main2():
import socket
s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
try:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send(bytes("Server approved connection\n", "UTF-8"))
print(repr(addr[1]) + ": " + str(c.recv(1024)))
continue
except (SystemExit, KeyboardInterrupt):
print("Exiting....")
c.close()
break
except Exception as ex:
import traceback
print("Fatal Error...." + str(ex))
print(traceback.format_exc())
c.close()
break
if __name__ == '__main__':
main2()
【问题讨论】:
-
“最佳”在什么意义上?这里需要权衡取舍(速度、准确性、复杂性、比特率)。
-
速度在我的情况下
标签: python python-3.x sockets