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?
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)
                Sending a dict with json like below worked in my program.
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)
                        Skip the json.loads() part. Send the json object as the json string and load it from the string at the TCP client.
Also check: Python sending dictionary throught TCP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With