Python Forum

Full Version: Machine actively refused it. External IP only
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
client code

 import threading
from pynput.keyboard import Key, Listener
import logging
import socket
import json
import time

SERVER = "Fake External IP because internet and all"
PORT = 5005

BUFF_SIZE = 4096


class MonitorKB(threading.Thread):
    def __init__(self):

        threading.Thread.__init__(self)
        self.lock = threading.Lock()

        self.kb_listener = Listener(
            on_press=self.on_press,
            on_release=self.on_release)

        self.depressed_key = None

    def on_press(self, key):
        self.lock.acquire()
        if self.depressed_key is None:
            try:
                self.depressed_key = key.char
            except AttributeError as e:
                if key == Key.esc:
                    return False
        print(self.depressed_key)
        self.lock.release()

    def on_release(self, key):
        self.lock.acquire()
        self.depressed_key = None
        print("None")
        self.lock.release()

    def run(self):
        stop_flag = False
        self.kb_listener.start()
        net = Network()
        while True:
            # exit the loop
            if not self.kb_listener.is_alive():
                break
            self.lock.acquire()
            if self.depressed_key is not None and stop_flag:
                stop_flag = False
                net.send_message(self.depressed_key)
            elif self.depressed_key is None and not stop_flag:
                stop_flag = True
                net.send_message("0")  # sends a motor stop to the bot
            self.lock.release()


class Network(object):
    def __init__(self, server=SERVER, port=PORT):
        self.server = server
        self.port = port
        # dont forget about blocking and non-blocking
        # blocking:
            # program will lose control after s.recv()
            # until data is found. Blocking the program from running
        # Non-blocking
            # will return all data in the read buffer
            # if there is not data it will return nothing and
            # give control back to the program

    def send_message(self, d):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.server, self.port))
        print("sending message")
        self.s.sendall(str.encode(json.dumps(d)))
        print("message sent")

    def recvall_timeout_message(self, timeout = .01):
        # self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # self.s.connect((self.server, self.port))
        total_data = []
        begin = time.time()
        while True:
            # print("receiving")
            # if you got some data, then break after wait sec
            if total_data and time.time() - begin > timeout:
                break
            # if you got no data at all, wait a little longer
            elif time.time() - begin > timeout * 2:
                break
        try:
            data = json.loads(self.s.recv(BUFF_SIZE).decode("utf-8"))
            print(data)
            if data:
                total_data.append(data)
            else:
                time.sleep(0.1)
        except:
            pass
        return total_data

    def recvall_timeout_file(self, timeout=.01):
        print(self.s)
        total_data = []

        begin = time.time()
        while True:
            # print("receiving")
            # if you got some data, then break after wait sec
            if total_data and time.time() - begin > timeout:
                break
            # if you got no data at all, wait a little longer
            elif time.time() - begin > timeout * 2:
                break
            try:
                data = self.s.recv(BUFF_SIZE)

                if data:
                    total_data.append(data)
                    begin = time.time()
                else:
                    time.sleep(0.1)
            except:
                pass
        print("left recvall_timeout_file")
        return total_data


if __name__ == "__main__":
    logging.basicConfig()
    monitorKB = MonitorKB()
    monitorKB.start()
    monitorKB.join()


Sever code

import socket
import json
import time
import sys
import threading

HOST = ''
PORT = 5005
BUFF_SIZE = 4096  # bytes


class Network(object):
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def socketConnect(self):
        self.s.bind((HOST, PORT))
        self.s.listen(1)

    def accept(self):
        self.conn, self.addr = self.s.accept()
        self.conn.setblocking(True)

    def send_message(self, d):
        print("sending message")
        print(str(d))
        self.conn.sendall(str.encode(json.dumps(d)))
        print("message sent")

    def recvall_timeout_message(self, timeout=.5):
        total_data = []

        begin = time.time()
        while True:

            # if you got some data, then break after wait sec
            if total_data and time.time() - begin > timeout:
                break
            # if you got no data at all, wait a little longer
            elif time.time() - begin > timeout * 2:
                break
        try:
            data = json.loads(self.conn.recv(BUFF_SIZE).decode("utf-8"))

            if data:
                total_data.append(data)
                begin = time.time()
            else:
                time.sleep(0.1)
        except:
            print("something happened")

        return total_data


class BotControl(object):
    """
        Controls the wheels motors for the bot
    """
    @staticmethod
    def control(key_char):
        if key_char == 'w':
            BotControl.forwards()
        elif key_char == 'a':
            BotControl.left()
        elif key_char == 's':
            BotControl.backwards()
        elif key_char == 'd':
            BotControl.right()
        elif key_char == 'q':
            BotControl.spin_left()
        elif key_char == 'e':
            BotControl.spin_right()
        elif key_char == "0":
            BotControl.stop()

    @staticmethod
    def forwards():
        print("Driving Forwards")

    @staticmethod
    def backwards():
        print("Driving Backwards")


    @staticmethod
    def left():
        print("Driving Left")


    @staticmethod
    def right():
        print("Driving Right")


    @staticmethod
    def spin_right():
        print("Spinning Right")


    @staticmethod
    def spin_left():
        print("Spinning Left")


    @staticmethod
    def stop():
        print("Stopping")



def main():
    net = Network()
    net.socketConnect()
    while True:
        net.accept()
        bot_command = net.recvall_timeout_message()
        BotControl.control(bot_command[0])
        print(bot_command[0])


if __name__ == "__main__":
    main()
I have a 2 router situation. I have opened port 5005 on both routers. The router connected to the PC and the VM is open for internal and external port 5005 for the servers local IP and the router connected to that router has the port 5005 open too the router connected to the PC and VM. when i use local ip address the client can connect to the server with no issue but when i use the external ip i get no connection could be made because the target machine actively refused it. I have disabled firewall to see if that was the issue. Any help would be very helpful.

Thank you.
Frustrated noob
Was using the incorrect internal IP address for the router that the bot was attached too. If anyone was wondering. The IP that you use to log into your router is not the same as the assigned ip that the second router gave my router. so if this is your issue that could be your solution too.