BW3-Core/boswatch/network/client.py

129 lines
4.5 KiB
Python
Raw Normal View History

2018-01-07 21:50:41 +01:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
@file: client.py
@date: 09.12.2017
@author: Bastian Schroll
@description: Class implementation for a TCP socket client
"""
import logging
import socket
import select
2018-01-07 21:50:41 +01:00
logging.debug("- %s loaded", __name__)
HEADERSIZE = 10
2018-01-07 21:50:41 +01:00
class TCPClient:
"""!TCP client class"""
def __init__(self, timeout=3):
2018-01-07 22:34:40 +01:00
"""!Create a new instance
2018-09-21 22:09:30 +02:00
@param timeout: timeout for the client in sec. (3)"""
2019-03-02 09:15:40 +01:00
self._sock = None
self._timeout = timeout
2018-01-07 21:50:41 +01:00
def connect(self, host="localhost", port=8080):
"""!Connect to the server
@param host: Server IP address ("localhost")
2018-01-07 21:50:41 +01:00
@param port: Server Port (8080)
@return True or False"""
try:
if not self.isConnected:
self._sock = socket
self._sock.setdefaulttimeout(self._timeout)
self._sock = socket.create_connection((host, port))
logging.debug("connected to %s:%s", host, port)
return True
2019-03-03 19:39:53 +01:00
logging.warning("client always connected")
return True
2018-01-07 21:50:41 +01:00
except ConnectionRefusedError:
2018-09-18 05:59:38 +02:00
logging.error("cannot connect to %s:%s - connection refused", host, port)
2018-02-22 07:34:36 +01:00
except socket.timeout: # pragma: no cover
2018-09-18 05:59:38 +02:00
logging.warning("cannot connect to %s:%s - timeout after %s sec", host, port, self._timeout)
2019-03-02 09:15:40 +01:00
return False
2018-01-07 21:50:41 +01:00
def disconnect(self):
"""!Disconnect from the server
@return True or False"""
try:
if self.isConnected:
self._sock.close()
self._sock = None
logging.debug("disconnected")
return True
logging.warning("client always disconnected")
2019-03-03 19:39:53 +01:00
return True
2018-01-07 21:50:41 +01:00
except AttributeError:
logging.error("cannot disconnect - no connection established")
2019-03-02 09:17:20 +01:00
return False
2018-01-07 21:50:41 +01:00
def transmit(self, data):
2018-01-07 22:34:40 +01:00
"""!Send a data packet to the server
2018-01-07 21:50:41 +01:00
@param data: data to send to the server
@return True or False"""
try:
2019-10-20 17:56:40 +02:00
if not self._sock: # check if socket is still available
logging.error("cannot receive - no connection established")
return False
2018-09-18 05:59:38 +02:00
logging.debug("transmitting: %s", data)
header = str(len(data)).ljust(HEADERSIZE)
self._sock.sendall(bytes(header + data, "utf-8"))
2018-01-07 21:50:41 +01:00
logging.debug("transmitted...")
return True
2018-01-11 13:01:27 +01:00
except ConnectionResetError:
logging.error("cannot transmit - host closed connection")
2019-03-02 09:15:40 +01:00
return False
2018-01-07 21:50:41 +01:00
def receive(self):
"""!Receive data from the server
@return received data"""
try:
if not self._sock: # check if socket is still available
2019-10-20 17:56:40 +02:00
logging.error("cannot receive - no connection established")
return False
read, _, _ = select.select([self._sock], [], [], 1)
if not read: # check if there is something to read
return False
header = self._sock.recv(HEADERSIZE)
if not len(header): # check if there data
return False
length = int(header.decode("utf-8").strip())
received = self._sock.recv(length).decode("utf-8")
logging.debug("received %d bytes: %s", length, received)
2018-01-07 21:50:41 +01:00
return received
2018-01-13 09:56:46 +01:00
except ConnectionResetError:
logging.error("cannot receive - host closed connection")
2018-02-22 07:34:36 +01:00
except socket.timeout: # pragma: no cover
logging.warning("cannot receive - timeout after %s sec", self._timeout)
2019-03-02 09:15:40 +01:00
return False
@property
def isConnected(self):
"""!Property of client connected state"""
if self._sock:
2019-09-20 18:19:46 +02:00
try:
aliveMsg = "<alive>"
header = str(len(aliveMsg)).ljust(HEADERSIZE)
self._sock.sendall(bytes(header + aliveMsg, "utf-8"))
2019-09-20 18:19:46 +02:00
return True
except (AttributeError, BrokenPipeError):
2019-10-20 17:56:40 +02:00
logging.error("Unknown error: ")
2019-10-20 17:37:37 +02:00
except ConnectionResetError:
2019-09-20 18:19:46 +02:00
pass
return False