OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

I don't receive any data in get_clients_from_signal_server p2p chat

  • Thread starter Thread starter Павел Бархотов
  • Start date Start date
П

Павел Бархотов

Guest
When I receive the list of connected users the program simply freezes and the server stops responding. It just shows the source in my terminal, but no message.

signal_server:

Code:
import socket
import threading
import json

clients = {}
lock = threading.Lock()

def handle_client(data, addr, sock):
    global clients
    try:
        message = json.loads(data.decode('utf-8'))
        print(f"Received message from {addr}: {message}")  # Debugging statement
        if 'register' in message:
            with lock:
                clients[message['name']] = addr
            response = {'status': 'registered', 'clients': list(clients.keys())}
            sock.sendto(json.dumps(response).encode('utf-8'), addr)
            print(f"Registered {message['name']} from {addr}")  # Debugging statement
        elif 'get_clients' in message:
            response = {'status': 'registered', 'clients': list(clients.keys())}
            sock.sendto(json.dumps(response).encode('utf-8'), addr)
            print(f"Sent client list to {addr}")  # Debugging statement
    except Exception as e:
        print(f"Error handling client {addr}: {e}")

def signal_server(host, port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind((host, port))
    print(f"Signal server started on {host}:{port}")

    while True:
        try:
            data, addr = server_socket.recvfrom(1024)
            threading.Thread(target=handle_client, args=(data, addr, server_socket)).start()
        except Exception as e:
            print(f"Error in main loop: {e}")

if __name__ == '__main__':
    signal_host = 'localhost'
    signal_port = 8001
    signal_server(signal_host, signal_port)

The client app code starts here and the get_clients_from_signal_server function sends a request to the server to get user data.

P2PClient:

Code:
import argparse
import socket
import sys
import time
import json
import threading

shutdown = False

class Message:
    def __init__(self, **data):
        self.status = 'online'
        for param, value in data.items():
            setattr(self, param, value)
        self.curr_time = time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime())

    def to_json(self):
        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)

class P2PClient:
    def __init__(self, host, port, name=None, signal_server_address=None):
        self.current_connection = None
        self.client_address = (host, port)
        self.name = name if name else f"{host}:{port}"
        self.signal_server_address = signal_server_address
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.client_address)

    def register_with_signal_server(self):
        if self.signal_server_address:
            message = {"register": True, "name": self.name}
            self.socket.sendto(json.dumps(message).encode('utf-8'), self.signal_server_address)
            data, _ = self.socket.recvfrom(1024)
            response = json.loads(data.decode('utf-8'))
            if response['status'] == 'registered':
                print(f"Registered with signal server. Current clients: {response['clients']}")

    def get_clients_from_signal_server(self):
        if self.signal_server_address:
            message = {"get_clients": True}
            print(f"Requesting client list from signal server at {self.signal_server_address}")  # Debugging statement
            self.socket.sendto(json.dumps(message).encode('utf-8'), self.signal_server_address)
            data, _ = self.socket.recvfrom(1024)
            response = json.loads(data.decode('utf-8'))
            print(f"Received clients from signal server: {response['clients']}")
            return response['clients']
        return []

...


    def run(self):
        global shutdown
        self.register_with_signal_server()
        recv_thread = threading.Thread(target=self.receive)
        recv_thread.start()
        while not shutdown:
            print("1. Get list of clients")
            print("2. Connect to client")
            print("3. Exit")
            choice = input("Choose an option: ")
            if choice == "1":
                clients = self.get_clients_from_signal_server()
                print("Available clients:")
                for client_name in clients:
                    print(f" - {client_name}")
            elif choice == "2":
                self.connect()
            elif choice == "3":
                shutdown = True
                print("Exiting...")
            else:
                print("Invalid option. Please try again.")
            time.sleep(1)
        recv_thread.join()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-ho", "--host", help="p2p client host ip address, like 127.0.0.1")
    parser.add_argument("-p", "--port", help="p2p client host port, like 8001")
    parser.add_argument("-sh", "--signalhost", help="signal server host ip address, like 127.0.0.1")
    parser.add_argument("-sp", "--signalport", help="signal server port, like 8000")
    args = parser.parse_args()
    try:
        host = args.host
        port = int(args.port)
        signal_host = args.signalhost
        signal_port = int(args.signalport)
        name = input("Name: ").strip()
        signal_server_address = (signal_host, signal_port)
        p2p_client = P2PClient(host, port, name=name, signal_server_address=signal_server_address)
        p2p_client.run()
    except (TypeError, ValueError):
        print("Incorrect arguments values, use --help/-h for more info.")

Bat files are written here to launch users. Server is starting on localhost 8001.

Code:
python p2p_client.py --host localhost --port 8002 --signalhost localhost --signalport 8001

Code:
python p2p_client.py --host localhost --port 8003 --signalhost localhost --signalport 8001
<p>When I receive the list of connected users the program simply freezes and the server stops responding. It just shows the source in my terminal, but no message.</p>
<p><code>signal_server</code>:</p>
<pre><code>import socket
import threading
import json

clients = {}
lock = threading.Lock()

def handle_client(data, addr, sock):
global clients
try:
message = json.loads(data.decode('utf-8'))
print(f"Received message from {addr}: {message}") # Debugging statement
if 'register' in message:
with lock:
clients[message['name']] = addr
response = {'status': 'registered', 'clients': list(clients.keys())}
sock.sendto(json.dumps(response).encode('utf-8'), addr)
print(f"Registered {message['name']} from {addr}") # Debugging statement
elif 'get_clients' in message:
response = {'status': 'registered', 'clients': list(clients.keys())}
sock.sendto(json.dumps(response).encode('utf-8'), addr)
print(f"Sent client list to {addr}") # Debugging statement
except Exception as e:
print(f"Error handling client {addr}: {e}")

def signal_server(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((host, port))
print(f"Signal server started on {host}:{port}")

while True:
try:
data, addr = server_socket.recvfrom(1024)
threading.Thread(target=handle_client, args=(data, addr, server_socket)).start()
except Exception as e:
print(f"Error in main loop: {e}")

if __name__ == '__main__':
signal_host = 'localhost'
signal_port = 8001
signal_server(signal_host, signal_port)
</code></pre>
<p>The client app code starts here and the <code>get_clients_from_signal_server</code> function sends a request to the server to get user data.</p>
<p><code>P2PClient</code>:</p>
<pre><code>import argparse
import socket
import sys
import time
import json
import threading

shutdown = False

class Message:
def __init__(self, **data):
self.status = 'online'
for param, value in data.items():
setattr(self, param, value)
self.curr_time = time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime())

def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)

class P2PClient:
def __init__(self, host, port, name=None, signal_server_address=None):
self.current_connection = None
self.client_address = (host, port)
self.name = name if name else f"{host}:{port}"
self.signal_server_address = signal_server_address
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.client_address)

def register_with_signal_server(self):
if self.signal_server_address:
message = {"register": True, "name": self.name}
self.socket.sendto(json.dumps(message).encode('utf-8'), self.signal_server_address)
data, _ = self.socket.recvfrom(1024)
response = json.loads(data.decode('utf-8'))
if response['status'] == 'registered':
print(f"Registered with signal server. Current clients: {response['clients']}")

def get_clients_from_signal_server(self):
if self.signal_server_address:
message = {"get_clients": True}
print(f"Requesting client list from signal server at {self.signal_server_address}") # Debugging statement
self.socket.sendto(json.dumps(message).encode('utf-8'), self.signal_server_address)
data, _ = self.socket.recvfrom(1024)
response = json.loads(data.decode('utf-8'))
print(f"Received clients from signal server: {response['clients']}")
return response['clients']
return []

...


def run(self):
global shutdown
self.register_with_signal_server()
recv_thread = threading.Thread(target=self.receive)
recv_thread.start()
while not shutdown:
print("1. Get list of clients")
print("2. Connect to client")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
clients = self.get_clients_from_signal_server()
print("Available clients:")
for client_name in clients:
print(f" - {client_name}")
elif choice == "2":
self.connect()
elif choice == "3":
shutdown = True
print("Exiting...")
else:
print("Invalid option. Please try again.")
time.sleep(1)
recv_thread.join()

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-ho", "--host", help="p2p client host ip address, like 127.0.0.1")
parser.add_argument("-p", "--port", help="p2p client host port, like 8001")
parser.add_argument("-sh", "--signalhost", help="signal server host ip address, like 127.0.0.1")
parser.add_argument("-sp", "--signalport", help="signal server port, like 8000")
args = parser.parse_args()
try:
host = args.host
port = int(args.port)
signal_host = args.signalhost
signal_port = int(args.signalport)
name = input("Name: ").strip()
signal_server_address = (signal_host, signal_port)
p2p_client = P2PClient(host, port, name=name, signal_server_address=signal_server_address)
p2p_client.run()
except (TypeError, ValueError):
print("Incorrect arguments values, use --help/-h for more info.")
</code></pre>
<p>Bat files are written here to launch users. Server is starting on localhost 8001.</p>
<pre><code>python p2p_client.py --host localhost --port 8002 --signalhost localhost --signalport 8001
</code></pre>
<pre><code>python p2p_client.py --host localhost --port 8003 --signalhost localhost --signalport 8001
</code></pre>
 
Top