我在Python 3.6中有一个非常简单的TCP服务器,我想用它来发送任意对象。
我可以使用以下代码发送一个简单的列表:
myList = [99, 88]
current_connection.send(bytes(myList))
但是,此代码失败,异常为'dict' object cannot be interpreted as an integer
。
myList = [99,88,{'a': 3},77]
current_connection.send(bytes(myList))
如何发送此list
,其中包含tuple
?
我还想发送一个这样的自定义对象:
myObject = customObject()
current_connection.send(bytes(myObject))
但是,该代码抛出异常cannot convert 'customObject' object to bytes
。发送自定义对象的正确方法是什么?
我应该使用除socket.send()之外的其他方法吗?
以下是完整的代码:
import socket
def listen():
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connection.bind(('localhost', 5555))
connection.listen(10)
while True:
current_connection, address = connection.accept()
while True:
data = current_connection.recv(2048)
try:
#myList = [99,88,{'a': 3},77]
myList = [99, 88]
current_connection.send(bytes(myList))
except Exception as e:
print(e)
print(data)
if __name__ == "__main__":
try:
listen()
except KeyboardInterrupt:
pass
print('done')
如果send()
无法完成我所描述的内容,是否有更有效的方式来发送数据?
答案 0 :(得分:1)
为什么不首先将列表转换为json并通过套接字传输,如:
.project-panel .pp-thumb a[title="Danger Zone"] {
background: url(https://couill.art/wp-content/uploads/2018/06/Danger-Zone-Logo-website-thumbnail.gif) no-repeat;
background-size: contain;
}
.project-panel .pp-thumb a[title="Dangerz"] {
background: url(https://couill.art/wp-content/uploads/2018/05/Thicc-girls-slim-boi.gif) no-repeat;
background-size: contain;
}
.project-panel .pp-thumb a[title="Danger II"] {
background: url(https://couill.art/wp-content/uploads/2018/05/trio-trompettes-rouge-1.gif) no-repeat;
background-size: contain;
}
.project-panel .pp-thumb a[title="About"] {
background: url(https://couill.art/wp-content/uploads/2018/05/chauve-souris-anim.gif) no-repeat;
background-size: contain;
}
收件人
myList = [99,88,{'a': 3},77]
current_connection.send(json.dumps(myList).encode())
我还想发送一个这样的自定义对象:
存在两种解决方案