'Python set up two sockets to send and receive msg between each other?

I am fairly new to Python network programming. Recently I am trying to achieve make two programs talk to each other(i.e., send and receive information bi-laterally).

In program A, I have:

server_ip = ('', 4001)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_ip)

while True:
    #continuously send and receive info to program B until some breaking condition reached

    server.sendto(json.dumps(some_data).encode("utf-8"), server_ip)
    recv_data = server.recv(1024)
# ...

In Program B, I have:

ADDR=('', 4001)
class Task()
    """
    """
    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        print('trying to connect to XXX')
        while True:
            try:
                self.client.connect(ADDR)
                break
            except:
                pass
        print('connected to XXX')

    def step(self):
        """
        This method will be called repeatedly
        """
        #...
        self.send_udp_data()
        self.get_data()

    def send_udp_data(self):
        #...
        self.client.sendall(bytes(control_cmd, encoding='utf-8'))
        print("Sending CMD")

    def get_data(self):
        while True:
            try:
                data = self.client.recv(10240)
                data = bytearray(data)
                data_dict=json.loads(data.decode('utf-8'))
            except Exception as e:
                #some error handling 

I got countless errors while trying to achieve aforementioned functionality. How can I ensure these two programs properly communicate to each other?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source