send a json message to a tcp server in python

To send a JSON message to a TCP server in Python, you can use the socket library to establish a connection to the server and the json library to encode your message into a JSON string. Here's an example code snippet:

main.py
import socket
import json

# Construct your message as a Python dictionary
message = {
    'name': 'Alice',
    'age': 30,
    'location': {
        'city': 'New York',
        'state': 'NY'
    }
}

# Encode the message as a JSON string
json_message = json.dumps(message)

# Open a TCP connection to the server
host = 'example.com'
port = 1234
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

# Send the JSON message to the server
sock.send(json_message.encode())

# Close the TCP connection
sock.close()
542 chars
28 lines

In this example, we first construct our message as a Python dictionary, then encode it into a JSON string using json.dumps(). We then open a TCP connection to the server using socket.socket() and socket.connect(), and send the JSON message to the server using socket.send(). Finally, we close the TCP connection using socket.close(). Note that we encode the message as bytes before sending it over the network using msg.encode().

related categories

gistlibby LogSnag