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

Time:02-08

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?

CodePudding user response:

This works:

Program 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}")

Program 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 get_data")

task = Task()
while True:
    task.step()
  •  Tags:  
  • Related