Home > Back-end >  UDP socket not receiving data from peer in python
UDP socket not receiving data from peer in python

Time:07-30

I have a p2p simple chat app in python. A server code receives the IP and port of peers and sends each peer address to another:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 44444))

while True:
    clients = []

    while True:
        data, address = sock.recvfrom(128)
        clients.append(address)
        sock.sendto(b'ready', address)

        if len(clients) == 2:
            break

    c1 = clients.pop()
    c2 = clients.pop()

    try:
        sock.sendto('{} {} {}'.format(c1[0], c1[1], c2[1]).encode(), c2)
        sock.sendto('{} {} {}'.format(c2[0], c2[1], c1[1]).encode(), c1)
    except Exception as e:
        print(str(e))

In my client code, first I start sending client info to the server (This part works properly):

import socket
import threading

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.bind(('', 40270))
    sock.sendto(b'0', ('X.X.X.X', 44444))

    while True:
        data = sock.recv(1024).decode()

        if data.strip() == 'ready':
            break

    ip, myport, dport = sock.recv(1024).decode().split(' ')
    myport = int(myport)
    dport = int(dport)

    print('\n ip: {} , myport: {} , dest: {}'.format(ip, myport, sport))

This part of the code starts listening to the server after sending the current client's info to the server and when the other client gets connected, it receives its IP and port.

After connecting two clients and exchanging their addresses, a p2p connection is established between them.

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.bind(('', myport))
    sock.sendto(b'0', (ip, dport))
    print('ready to exchange messages\n')

Then, I run a thread to start listening to the other client like this:

def listen():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', myport))

        while True:
            data = s.recv(1024)
            print('\rpeer: {}\n> '.format(data.decode()), end='')


listener = threading.Thread(target=listen, daemon=True)
listener.start()

Also, another socket is responsible to send messages:

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('', myport))

    while True:
        msg = input('> ')
        s.sendto(msg.encode(), (ip, dport))

After all, as I said before, the server exchange the IP and port of clients properly. But messages were not received by another client after sending. I think the problem is about the wrong port choice while I do the exchange.

Regards.

CodePudding user response:

It is completely functional on Linux. The problem just occurred on a windows machine.

  • Related