[英]Encoding 2D List
How can I encode 2D List here to send to the server, so that server can print the 2D List?如何在此处编码 2D List 以发送到服务器,以便服务器可以打印 2D List?
ERROR: AttributeError: 'list' object has no attribute 'encode'错误:AttributeError:“列表”对象没有“编码”属性
CODE:代码:
Client.py
from socket import *
serverName = "localhost"
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
input = [
[1, 0, 1, 1, 0],
[1, 0, 0, 1, 0],
[1, 1, 1, 0, 1]
]
clientSocket.send(input.encode())
clientSocket.close()
Server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("The server is ready to receive!")
while True:
connectionSocket, addr = serverSocket.accept()
array = connectionSocket.recv(1024).decode()
print(array)
connectionSocket.close()
If you only want the peer to be able to print , or send back the 2D list, you can directly send a string representation:如果您只希望对等方能够打印或发回 2D 列表,则可以直接发送字符串表示:
clientSocket.send(str(input).encode())
If you want it to be able to process the data as a 2D list, you should serialize the list, for example with json:如果您希望它能够将数据作为 2D 列表处理,您应该序列化列表,例如使用 json:
clientSocket.send(json.dumps(input).encode())
Then you can retrieve the list with:然后您可以使用以下命令检索列表:
list2D = json.loads(connectionSocket.recv(1024))
the simplest way to do it is to use serialization like JSON .最简单的方法是使用像JSON这样的序列化。 Here is an example with your code, its convert your list into a JSON string and then to bytes before sending it:
Client.py
这是您的代码示例,它将您的列表转换为 JSON 字符串,然后在发送之前将其转换为字节:
Client.py
from socket import *
import json
serverName = "localhost"
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
input = [
[1, 0, 1, 1, 0],
[1, 0, 0, 1, 0],
[1, 1, 1, 0, 1]
]
clientSocket.send(json.dumps(input).encode('utf8'))
clientSocket.close()
Server.py
from socket import *
import json
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("The server is ready to receive!")
while True:
connectionSocket, addr = serverSocket.accept()
array = json.loads(connectionSocket.recv(1024).decode('utf8'))
print(array)
connectionSocket.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.