Python 设置两个套接字来相互发送和接收消息?

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

我对 Python 网络编程还很陌生。最近我正在尝试实现让两个程序相互对话(即双向发送和接收信息)。

在程序A中,我有:

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)
# ...

在程序B中,我有:

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 

我在尝试实现上述功能时遇到了无数错误。我怎样才能确保这两个程序正确地相互通信?

这个有效:

程序A:

import json
import socket

ADDR_A = ('', 4001)
ADDR_B = ('', 4002)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(ADDR_A)

while True:
    #continuously send and receive info to program B until some breaking condition reached
    print("A sending...")
    some_data = "This is some data sent by A"
    # Note: this will be silently dropped if the client is not up and running yet
    # And even if the the client is running, it may still be silently dropped since UDP is unreliable.
    sock.sendto(json.dumps(some_data).encode("utf-8"), ADDR_B)
    print("A receiving...")
    recv_data = sock.recv(1024)
    print(f"A received {recv_data}")

程序B:

import json
import socket

ADDR_A = ('', 4001)
ADDR_B = ('', 4002)
class Task():
    """
    """
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(ADDR_B)

    def step(self):
        """
        This method will be called repeatedly
        """
        print("B step")
        self.send_data()
        self.receive_data()

    def send_data(self):
        control_cmd = "This is a control command sent by B"
        print("B sending...")
        self.sock.sendto(bytes(control_cmd, encoding='utf-8'), ADDR_A)
        print(f"B sent {control_cmd}")

    def receive_data(self):
        try:
            data = self.sock.recv(10240)
            print(f"B received raw data {data}")
            data = bytearray(data)
            data_dict=json.loads(data.decode('utf-8'))
            print(f"B received JSON {data_dict}")
        except Exception as e:
            print(f"B exception {e} in receive_data")

task = Task()
while True:
    task.step()