send a json message to a udp server in python

To send a JSON message to a UDP server in Python, you can use the socket module. Here is an example code block that shows how to do this:

main.py
import json
import socket

# Define the host and port of the UDP server
HOST = 'localhost'
PORT = 12345

# Define the JSON object to send
json_obj = {'key1': 'value1', 'key2': 'value2'}

# Serialize the JSON object to string format
json_str = json.dumps(json_obj)

# Create a UDP socket and send the message
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.sendto(json_str.encode(), (HOST, PORT))
420 chars
17 lines

In this code, we import the json and socket modules. We then define the host and port of the UDP server that we want to send the message to.

Next, we define the JSON object that we want to send, and serialize it to a string format using the json.dumps() method.

Finally, we create a UDP socket using the socket.socket() method, and send the message to the server using the sock.sendto() method, passing in the encoded JSON string and the server address as parameters.

With this code block, you can easily send a JSON message to a UDP server in Python.

gistlibby LogSnag