Пример #1
0
def Main():
    address = {}

    connection = ConnectionHandler()
    connection.startAP('ESP32_AP', '12312312')
    _thread.start_new_thread(connection.startWlanClient,
                             ('Pretty Fly for a Wi-Fi', 'abyssus64'))

    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(
        socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
    )  # tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire

    try:
        soc.bind(('192.168.4.1', 8888))
    except OSError as exc:
        print("Error: Bind failed! ErrorNo:", exc.args[0])
        sys.exit()

    soc.listen(5)  # queue up to 5 requests
    print("Socket now listening...")

    createFilePath()
    # infinite loop- do not reset for every requests
    while True:
        sock, address = soc.accept()
        ip, port = str(address[0]), str(address[1])
        print("Client [" + ip + ":" + port + "] connected!")

        pin_handler.toggleLed()
        try:
            _thread.start_new_thread(clientThread, (sock, ip, port))
        except:
            print("Unable to start the thread!")
    def setup(self):
        # Add server socket to the list of readable connections
        self.connection_handler = ConnectionHandler(self.server_socket,
                                                    self.buffer, self.local_ip)

        # Setup server handlers
        self.file_handler = FileHandler()
        self.data_handler = self.connection_handler.get_data_handler()

        # Runtime vars
        self.run_server = True
        self.session_name = datetime.datetime.now()
Пример #3
0
    def start(self):
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind((self.host, self.port))
        self.s.listen(5)

        while True:
            c, addr = self.s.accept()
            ConnectionHandler(c, addr).start()
Пример #4
0
def top_search_impl(start=0, end=10):
    db = ConnectionHandler().get_connection()
    cursor = db.cursor()
    cursor.execute(
        'select * from indexToResultCounts order by count desc limit %s offset %s',
        [(end - start), start])
    results = cursor.fetchall()
    res = []
    for result in results:
        dict = {
            "paperTitle": result[1],
            "paperUrl": result[3],
            "count": result[4]
        }
        res.append(dict)
    db.close()
    return res
Пример #5
0
def startServer(ip, port):
    fileName = input("Enter filename for the new file: ")
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((ip, port))

    ch = ConnectionHandler(sock, 100, 1, fileName)
    try:
        ch.serve()
    except KeyboardInterrupt:
        ch.endAllConnections()
        print("Server stopped")
Пример #6
0
def update_count(index, title, abstract, url):
    if not isinstance(index, str):
        print('[ERROR] Wrong type')
        return
    db = ConnectionHandler().get_connection()
    cursor = db.cursor()
    rows_affected = cursor.execute(
        'update indexToResultCounts set count = count+1 where docId=%s',
        (index, ))
    if rows_affected == 0:
        print('[INFO] Creating entry')
        cursor.execute(
            "insert into indexToResultCounts values(%s, %s, %s, %s, 1);",
            (index, title, abstract, url))
    db.commit()
    db.close()
Пример #7
0
def startClient(ip, port):
    fileName = input("Enter filename: ")

    # launch localhost client connecting to server
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("0.0.0.0", random.randint(10000, 60000)))

    ch = ConnectionHandler(sock, 100, 0.1)

    # create connection
    streamID = random.randint(0, 2 ^ 32 - 1)
    c = ClientConnection((ip, port), ch, streamID, 100, 1, fileName)

    # client sends content to server
    ch.addConnection(c)
    ch.serve()
    print("File sent biatch!")
 def __init__(self, client_index):
     self.run_client = True
     self.client_connected = True
     self.client_index = client_index
     self.connection_handler = ConnectionHandler(str(client_index))
class SocketClient:
    def __init__(self, client_index):
        self.run_client = True
        self.client_connected = True
        self.client_index = client_index
        self.connection_handler = ConnectionHandler(str(client_index))

    def setup(self):
        self.connection_handler.socket_create()
        self.connection_handler.socket_connect()
        self.setup_sensor()

    def setup_sensor(self):
        while True:
            try:
                self.sensor = Sensor(self.client_index)
                print ("\33[32m\33[1mSuccessfully setup sensor \33[0m")
                break
            except Exception as e:
                print ("\33[31m\33[1mError setting up the sensor \33[0m")
                print (e)
                time.sleep(1)

    def read_sensor(self):
        try:
            sensor_data = self.sensor.get_data()
            return pickle.dumps(sensor_data)
        except Exception as e:
            print ("\n\33[93m\33[1mReinitalising sensor \33[0m")
            print (e)
            self.setup_sensor()

    def send(self):
        try:
            # print("Send to server")
            pickle_data = self.read_sensor()
            self.connection_handler.socket_send(pickle_data)
        except Exception as e:
            print (e)

    def listen(self):
        self.setup()
        while self.run_client:
            socket_code = self.connection_handler.connection_listen()
            self.execute_code(socket_code)

    def execute_code(self, socket_code):
        if socket_code == "send_data":
            self.send()
        elif socket_code == "calibrate":
            print("Calibration call")
            self.sensor.calibrate()
        elif socket_code == "disconnect_all":
            print("Disconnecting client")
            self.connection_handler.socket_close()
            self.run_client = False

    def monitor(self):
        while self.run_client:
            self.client_connected = self.connection_handler.check_connection()
            # print("Check connected", self.client_connected)
            time.sleep(1)

    def finish(self):
        self.connection_handler.socket_close()
        sys.exit()
Пример #10
0
server_host = args.host
server_port = args.port

logger = logging.getLogger('Client')
logger.setLevel(LOGGING_LEVEL)
fh = logging.FileHandler(LOGFILE)
fh.setLevel(LOGGING_LEVEL)
ch = logging.StreamHandler()
ch.setLevel(LOGGING_LEVEL)
formatter = logging.Formatter(LOGGING_FORMAT)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

loop = asyncio.get_event_loop()
connectivity_manager = ConnectivityManager(LOGGING_LEVEL, fh, ch)
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
                                         cafile=ca_filepath)
ssl_context.check_hostname = False
ssl_context.load_cert_chain(cert_filepath, key_filepath)
client_coro = loop.create_connection(
    lambda: ConnectionHandler(connectivity_manager),
    server_host,
    server_port,
    ssl=ssl_context)
try:
    while True:
        loop.run_until_complete(client_coro)
except asyncio.CancelledError:
    loop.close()
Пример #11
0
                    "--timeout",
                    help="Define bTCP timeout in milliseconds",
                    type=int,
                    default=5)
parser.add_argument("-i", "--input", help="File to send", default="tmp.file")
args = parser.parse_args()

server_ip = "127.0.0.1"
server_port = 9002

sock = socket.socket(
    socket.AF_INET,
    socket.SOCK_DGRAM)  #socketWrapper.perfectSocket(("localhost",9001)) # UDP
sock.bind((server_ip, server_port))

ch = ConnectionHandler(sock, args.window, args.timeout)

# get file to send
fileName = "text.txt"  # input("Enter file name: ")

# create connection
streamID = 1111
c = ClientConnection(("127.0.0.1", 9001), ch, streamID, args.window,
                     args.timeout, fileName)

# add connection
ch.addConnection(c)

try:
    ch.serve()
Пример #12
0
logger = logging.getLogger('Server')
logger.setLevel(LOGGING_LEVEL)
fh = logging.FileHandler(LOGFILE)
fh.setLevel(LOGGING_LEVEL)
ch = logging.StreamHandler()
ch.setLevel(LOGGING_LEVEL)
formatter = logging.Formatter(LOGGING_FORMAT)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

with open(accounts_json_filepath) as accounts_json_file:
  accounts_json = json.load(accounts_json_file)

usernames = [None] * len(accounts_json)
names = {}
for i in range(len(accounts_json)):
  account_json = accounts_json[i]
  usernames[i] = username = account_json["username"]
  names[username] = account_json["name"]

loop = asyncio.get_event_loop()
connectivity_manager = ConnectivityManager(usernames, names, LOGGING_LEVEL, fh, ch)
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=ca_filepath)
ssl_context.load_cert_chain(cert_filepath, key_filepath)
ssl_context.verify_mode = ssl.CERT_REQUIRED
server_coro = loop.create_server(lambda: ConnectionHandler(connectivity_manager), server_host, server_port, ssl=ssl_context)
server = loop.run_until_complete(server_coro)
loop.run_forever()
Пример #13
0
HOST = '127.0.0.1'
PORT = 27972

BUFFER_SIZE = 4096

sel = selectors.DefaultSelector()

sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockets.bind((HOST, PORT))
sockets.listen()
sockets.setblocking(False)

sel.register(sockets, selectors.EVENT_READ, data=None)
print("The server is listening at host: {}, port {}".format(HOST, PORT))

_connection_handler = ConnectionHandler()


####################################
def accept_wrapper(sock):
    connection, address = sock.accept()
    print("Connection established: {}".format(address))
    connection.setblocking(False)

    data = types.SimpleNamespace(addr=address, inb=b'', outb=b'')
    events = selectors.EVENT_READ | selectors.EVENT_WRITE
    sel.register(connection, events, data=data)


def service_connection(key, mask):
    sock = key.fileobj
class SocketServer:
    def __init__(self):
        self.buffer = 4096
        self.port = 5001
        self.local_ip = self.get_ip()
        self.create_socket()

    def create_socket(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while True:
            try:
                self.server_socket.bind((self.local_ip, self.port))
                self.server_socket.listen(10)
                break
            except Exception as e:
                print("Couldnt create socket server\t", e, "\t",
                      datetime.datetime.now().time().strftime('%H:%M:%S'))
            time.sleep(1)

    def get_ip(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('10.255.255.255', 1))
            ip = s.getsockname()[0]
        except Exception as e:
            print(e)
            print(ip)
        finally:
            s.close()
        return ip

    def setup(self):
        # Add server socket to the list of readable connections
        self.connection_handler = ConnectionHandler(self.server_socket,
                                                    self.buffer, self.local_ip)

        # Setup server handlers
        self.file_handler = FileHandler()
        self.data_handler = self.connection_handler.get_data_handler()

        # Runtime vars
        self.run_server = True
        self.session_name = datetime.datetime.now()

    def run_listen(self):
        print("\33[32m \t\t\t\tSocket Server Running \33[0m")
        while self.run_server:
            self.connection_handler.check_connections()
        # Close socket
        try:
            self.connection_handler.disconnect_all()
            self.server_socket.shutdown(socket.SHUT_RDWR)
            self.server_socket.close()
        except Exception as e:
            # print(e)
            x = 1

    def run_send(self):
        while self.run_server:
            try:
                #print('Request data')
                self.connection_handler.send_to_all('send_data')
            except Exception as e:
                # print('Error requesting sensor data')
                x = 1
            time.sleep(.1)

    def record_data(self):
        while self.run_server:
            try:
                self.file_handler.record_data(
                    self.data_handler.get_rower_dicts())
            except Exception as e:
                print(e)
                # x=1
            time.sleep(.1)

    def finish(self):
        print("Closing socket")
        self.run_server = False

    def get_latest_data(self, rower_index):
        return self.data_handler.get_rower_json(int(rower_index))

    def server_request(self, socket_code):
        if socket_code == "session_start":
            print("Start session")
            self.file_handler.set_session_status(True)
        elif socket_code == "session_end":
            print("End session")
            self.file_handler.set_session_status(False)
        elif socket_code == "disconnect_all":
            print("Disconnect clients")
            self.connection_handler.disconnect_all(socket_code)
        else:
            self.connection_handler.send_to_all(socket_code)
Пример #15
0
def connect(address):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((address, 9525))
    return ConnectionHandler(sock)