如何在python中使用tcp套接字发送json对象

Loc*_*ara 10 python sockets json tcp

这是我的python tcp客户端.我想将一个json对象发送到server.But我不能使用sendall()方法发送对象.我怎样才能做到这一点?

import socket
import sys
import json

HOST, PORT = "localhost", 9999

m ='{"id": 2, "name": "abc"}'
jsonObj = json.loads(m)


data = jsonObj

# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(jsonObj)


    # Receive data from the server and shut down
    received = sock.recv(1024)
finally:
    sock.close()

print "Sent:     {}".format(data)
print "Received: {}".format(received)
Run Code Online (Sandbox Code Playgroud)

har*_*rry 8

在我的程序中使用如下所示的 json 发送字典是有效的。

import socket
import sys
import json

HOST, PORT = "localhost", 9999

#m ='{"id": 2, "name": "abc"}'
m = {"id": 2, "name": "abc"} # a real dict.


data = json.dumps(m)

# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data,encoding="utf-8"))


    # Receive data from the server and shut down
    received = sock.recv(1024)
    received = received.decode("utf-8")

finally:
    sock.close()

print "Sent:     {}".format(data)
print "Received: {}".format(received)

Run Code Online (Sandbox Code Playgroud)


Moi*_*dri 5

跳过该json.loads()部分。将 json 对象作为 json 字符串发送,并在 TCP 客户端从该字符串加载它。

另请检查:Python 通过 TCP 发送字典

  • 不,您不能发送 JSON 对象。您需要首先将其序列化 (2认同)