Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a json object using tcp socket in python

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)
like image 809
Lochana Thenuwara Avatar asked Oct 02 '16 13:10

Lochana Thenuwara


2 Answers

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)

like image 88
harry Avatar answered Oct 01 '22 05:10

harry


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

like image 21
Moinuddin Quadri Avatar answered Oct 01 '22 06:10

Moinuddin Quadri