0

I am trying to create a system contains network of computers where there is a master and multiple slaves. The master device would send commands over socket and slaves would answer to the commands. I found a useful material here and it worked. I was able to send data and receive answers.

So I decided to create a class for it to have server and client objects. When I created the Server and Client objects, the client object was working fine. But the Server Object although it looks like it working but it refuses connection.

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

Here my class:

import socket
from _thread import start_new_thread

class Communicator:
    class Server:
        def __init__(self, port, max_trans_length=128, logger=None):
            self.logger = logger or getLogger("dummy")
            self.port = port
            self.ServerSocket = socket.socket()
            self.mtl = max_trans_length
            self.ThreadCount = 0
            self.ServerSocket.bind((socket.gethostname(), self.port))

        def threaded_client(self, connection):
            connection.send(str.encode('Welcome to the Server'))
            while True:
                data = connection.recv(self.mtl)
                reply = f"Received: {data.decode('utf-8')}"
                if not data:
                    break
                connection.sendall(str.encode(reply))
            connection.close()

        def listen(self):
            print('Waiting for a Connection..')
            self.ServerSocket.listen(5)
            while True:
                Client, address = self.ServerSocket.accept()
                print('Connected to: ' + address[0] + ':' + str(address[1]))
                start_new_thread(self.threaded_client, (Client,))
                self.ThreadCount += 1
                print('Thread Number: ' + str(self.ThreadCount))
            self.ServerSocket.close()

    class Client:
        def __init__(self, host, port, max_trans_length=128, logger=None):
            self.logger = logger or getLogger("dummy")
            self.host = host
            self.port = port
            self.mtl = max_trans_length
            self.ClientSocket = socket.socket()
            print('Waiting for connection')
            self.ClientSocket.connect((host, port))
            _ = self.ClientSocket.recv(self.mtl)

        def transmit(self, data):
            self.ClientSocket.send(str.encode(data))
            response = self.ClientSocket.recv(self.mtl)
            print(response.decode('utf-8'))

        def disconnect(self):
            self.ClientSocket.close()

And here what i get: The error I get

I get similar error when I use a Linux machine.

MSH
  • 1,743
  • 2
  • 14
  • 22

1 Answers1

0

So after lots of searching I found out socket.gethostname() restricts the listening. Changing it with a black string or "127.0.0.1" solved the problem for me.

MSH
  • 1,743
  • 2
  • 14
  • 22