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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39817641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:45:20  来源:igfitidea点击:

How to send a json object using tcp socket in python

pythonjsonsocketstcp

提问by Lochana Thenuwara

here is my python tcp client. I want to send a json object to the server.But I can't send the object using the sendall() method. how can I do this?

这是我的 python tcp 客户端。我想向服务器发送一个 json 对象。但我无法使用 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)

回答by Moinuddin Quadri

Skip the json.loads()part. Send the json object as the json string and load it from the string at the TCP client.

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

Also check: Python sending dictionary throught TCP

还要检查:Python sent dictionary throught TCP

回答by Yuseferi

AS you can find out from Python sending dictionary through TCPit better convert the JSON object to a dictionary and using the following snippet

正如您可以从Python 通过 TCP 发送字典中发现的那样, 它更好地将 JSON 对象转换为字典并使用以下代码段

import json
data = json.load(open("data.json"))
 //or 
data = json.load('{"id": 2, "name": "abc"}')

type(data)
print(data[<keyFromTheJsonFile>])

You should serialize it with pickle:

您应该使用pickle以下命令对其进行序列化:

import pickle
dict = {...}
tcp_send(pickle.dumps(dict))

And on the other end:

而在另一端:

import pickle
dict = pickle.loads(tcp_recieve())

If the other end is not written in python, you can use a data serialization format, like xml, jsonor yaml.

如果另一端不是用python编写的,可以使用数据序列化格式,如xmljsonyaml

回答by harry

Sending a dict with json like below worked in my program.

在我的程序中使用如下所示的 json 发送 dict。

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)