pysocklib


Namepysocklib JSON
Version 0.6.1 PyPI version JSON
download
home_page
SummaryLibrary to work with socket clients and servers.
upload_time2023-12-11 21:09:25
maintainer
docs_urlNone
author
requires_python>=3.11
licenseMIT License Copyright (c) 2023 Daniel Ibarrola Sánchez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords socket client server
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # PySockLib

Helper library to implement socket client and servers as well as services to process, store, or 
send data received or send trough sockets.

## Installation

Create a virtual environment and activate it:

```shell
python3.11 -m venv venv
source venv/bin/activate
```

Install the latest version:

```shell
pip install pysocklib
```

## Python module

The python module contains several classes to easily implement client and/or server
programs. All available classes are listed below.

### ServerReceiver

A server that receives messages from a single client.

#### Constructor

```python
def __init__(
    self,
    address: tuple[str, int],
    received: Optional[queue.Queue[bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop: Optional[Callable[[], bool]] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)
```

- `address`: A tuple representing the IP address and port number to bind the server to.
- `received`: Optional queue to store received messages.
- `reconnect`: If True, the server will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop`: A function that returns True to signal the server to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging server events.

#### Properties
- `ip`: The IP address component of the server's address.
- `port`: The port number component of the server's address.
- `received`: The queue containing received messages.

#### Methods
- `listen()`: Creates the socket and puts it in listen mode.
- `accept_connection()`: Accepts a new connection.
- `start()`: Starts the server in a new thread.
- `join()`: Waits for the server thread to finish.
- `shutdown()`: Signals the server to shut down gracefully.
- `close_connection()`: Closes the client connection and the socket.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point. Closes all sockets

### ServerSender

#### Constructor

```python
def __init__(
    self,
    address: tuple[str, int],
    to_send: Optional[queue.Queue[str | bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop: Optional[Callable[[], bool]] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)
```

- `address`: A tuple representing the IP address and port number to bind the server to.
- `to_send`: Optional queue to store messages that will be sent.
- `reconnect`: If True, the server will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop`: A function that returns True to signal the server to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging server events.

#### Properties
- `ip`: The IP address component of the server's address.
- `port`: The port number component of the server's address.
- `to_send`: The queue containing messages to be sent.

#### Methods
- `listen()`: Creates the socket and puts it in listen mode.
- `accept_connection()`: Accepts a new connection.
- `start()`: Starts the server in a new thread.
- `join()`: Waits for the server thread to finish.
- `shutdown()`: Signals the server to shut down gracefully.
- `close_connection()`: Closes the client connection and the socket.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point. Closes all sockets

### Server

A server that sends and receives messages to and from a single client.
This server runs in two threads, one to send messages and another to receive messages.

```Python
def __init__(
    self,
    address: tuple[str, int],
    received: Optional[queue.Queue[bytes]] = None,
    to_send: Optional[queue.Queue[str | bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop_receive: Optional[Callable[[], bool]] = None,
    stop_send: Optional[Callable[[], bool]] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)

```

- `address`: A tuple representing the IP address and port number to bind the server to.
- `received`: Optional queue to store received messages.
- `to_send`: Optional queue containing messages to be sent.
- `reconnect`: If True, the server will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop_receive`:  A function that returns True to signal the receiving loop to stop.
- `stop_send`:  A function that returns True to signal the sending loop to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging server events.

#### Properties
- `received`: The queue containing received messages.
- `to_send`: The queue containing messages to be sent.
- `send_thread`: The thread responsible for sending messages.
- `receive_thread`: The thread responsible for receiving messages.

#### Methods
- `listen()`: Creates the socket and puts it in listen mode.
- `accept_connection()`: Accepts a new connection.
- `start()`: Starts the server in a new thread.
- `join()`: Waits for both the sending and receiving threads to stop.
- `shutdown()`: Signals the server to shut down gracefully.
- `close_connection()`: Closes the client connection and the socket.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point. Closes all sockets

### ClientReceiver

A client that receives messages from a server.

#### Constructor

```python
def __init__(
    self,
    address: tuple[str, int],
    received: Optional[queue.Queue[bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop: Optional[Callable[[], bool]] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)
```

- `address`: A tuple representing the IP address and port number to connect to.
- `received`: Optional queue to store received messages.
- `reconnect`: If True, the client will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop`: A function that returns True to signal the client to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging client events.

#### Properties

- `ip`: The IP address component of the client's address.
- `port`: The port number component of the client's address.
- `received`: The queue containing received messages.

#### Methods
- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.
- `start()`: Starts the client in a new thread.
- `join()`: Waits for the client thread to finish.
- `shutdown()`: Signals the client to shut down gracefully.
- `close_connection()`: Closes the socket connection.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point.

### ClientSender

```python
def __init__(
    self,
    address: tuple[str, int],
    to_send: Optional[queue.Queue[bytes | bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop: Optional[Callable[[], bool]] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)
```

- `address`: A tuple representing the IP address and port number to connect to.
- `to_send`: Optional queue to store messages to be sent.
- `reconnect`: If True, the client will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop`: A function that returns True to signal the client to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging client events.

#### Properties

- `ip`: The IP address component of the client's address.
- `port`: The port number component of the client's address.
- `to_send`: The queue containing messages to be sent.

#### Methods
- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.
- `start()`: Starts the client in a new thread.
- `join()`: Waits for the client thread to finish.
- `shutdown()`: Signals the client to shut down gracefully.
- `close_connection()`: Closes the socket connection.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point.

### Client

A client that sends and receives messages to and from a server.

```python
def __init__(
    self,
    address: tuple[str, int],
    received: Optional[queue.Queue[bytes]] = None,
    to_send: Optional[queue.Queue[str | bytes]] = None,
    reconnect: bool = True,
    timeout: Optional[float] = None,
    stop_receive: Callable[[], bool] = None,
    stop_send: Callable[[], bool] = None,
    stop_reconnect: Optional[Callable[[], bool]] = None,
    logger: Optional[logging.Logger] = None,
)
```
- `address`: A tuple representing the IP address and port number to connect to.
- `received`: Optional queue to store received messages.
- `to_send`: Optional queue containing messages to be sent.
- `reconnect`: If True, the client will attempt to reconnect after disconnection.
- `timeout`: Optional timeout value for send and receive operations.
- `stop_receive`: A function that returns True to signal the receiving loop to stop.
- `stop_send`: A function that returns True to signal the sending loop to stop.
- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have
any effect if reconnect is set to False.
- `logger`: Optional logger for logging client events.

#### Properties

- `ip`: The IP address component of the client's address.
- `port`: The port number component of the client's address.
- `received`: The queue containing received messages.
- `to_send`: The queue containing messages to be sent.
- `send_thread`: The thread responsible for sending messages.
- `receive_thread`: The thread responsible for receiving messages.

#### Methods
- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.
- `start()`: Starts the client in a new thread.
- `join()`: Waits for the client thread to finish.
- `shutdown()`: Signals the client to shut down gracefully.
- `close_connection()`: Closes the socket connection.
- `__enter__()`: Context manager entry point.
- `__exit__(...)`: Context manager exit point.


### AbstractService

This abstract base class is a blueprint  to easily create other services that communicate with each other trough queues. Very useful
for processing, storing, etc. the data received trough sockets.

Abstract base class for all services.

To add a new service, implement the `_handle_message` method.

A service consists of an input queue and an output queue. The purpose of a service is to apply some function to the inputs to obtain the outputs that can then be processed by another service or sent to a receptor.

Most services are meant to run indefinitely, and so they do not run in the main thread. However, a custom function to terminate the service when needed can be used, and the service can also run in the main thread if necessary.

#### Constructor

```python
def __init__(
            self,
            in_queue: Optional[queue.Queue] = None,
            out_queue: Optional[queue.Queue] = None,
            stop: Optional[Callable[[], bool]] = None,
            events: Optional[dict[str, threading.Event]] = None,
            logger: Optional[logging.Logger] = None,
    ):
```

#### Parameters:

- `in_queue` (Optional[queue.Queue]): Input queue for receiving messages.
- `out_queue` (Optional[queue.Queue]): Output queue for sending messages.
- `stop` (Optional[Callable[[], bool]]): Custom stop function.
- `events` (Optional[dict[str, threading.Event]]): Dictionary of events.
- `logger` (Optional[logging.Logger]): Logger for logging events.

### Examples 

Sample usage of a client that sends receives data from a server. The `client.py` program
will use a custom `MessageLogger` service to log all the data it receives, while the
`server.py` program whill use a service `MessageGenerator`to generate messages continuously
and send them to the client.

```python
# client.py
from socketlib import ClientReceiver
from socketlib.services.samples import MessageLogger
from socketlib.utils.logger import get_module_logger

if __name__ == "__main__":

    address = ("localhost", 12345)
    client = ClientReceiver(address, reconnect=True)
    
    logger = get_module_logger(__name__, "dev")
    msg_logger = MessageLogger(client.received, logger)
    
    with client:
        client.connect()
        client.start()
        msg_logger.start()
        
        try:
            client.join()
        except KeyboardInterrupt:
            client.shutdown()
            msg_logger.shutdown()

```

```python
# server.py
from socketlib import ServerSender, get_module_logger
from socketlib.services.samples import MessageGenerator


if __name__ == "__main__":

    address = ("localhost", 12345)
    server = ServerSender(address)
    
    logger = get_module_logger(__name__, "dev", use_file_handler=False)
    msg_gen = MessageGenerator(server.to_send, logger)
    
    with server:
        server.start()
        msg_gen.start()
        
        try:
            server.join()
        except KeyboardInterrupt:
            server.shutdown()
            msg_gen.shutdown()

```

## Developing

Developed in Python 3.11.4

Installing the development environment:

```shell
git clone https://github.com/Daniel-Ibarrola/MServ
python3.11 -m venv venv
source venv/bin/activate
pip install -r requirements/dev.txt
pip install -e .
```

## License

`pysocklib` was created by Daniel Ibarrola. It is licensed under the terms
of the MIT license.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "pysocklib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": "",
    "keywords": "socket,client,server",
    "author": "",
    "author_email": "Daniel Ibarrola <daniel.ibarrola.sanchez@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/53/34/3d6c5c354d2e0cffc3205538fd0d03decbcfed8c974eff738c10c8fa75f8/pysocklib-0.6.1.tar.gz",
    "platform": null,
    "description": "# PySockLib\n\nHelper library to implement socket client and servers as well as services to process, store, or \nsend data received or send trough sockets.\n\n## Installation\n\nCreate a virtual environment and activate it:\n\n```shell\npython3.11 -m venv venv\nsource venv/bin/activate\n```\n\nInstall the latest version:\n\n```shell\npip install pysocklib\n```\n\n## Python module\n\nThe python module contains several classes to easily implement client and/or server\nprograms. All available classes are listed below.\n\n### ServerReceiver\n\nA server that receives messages from a single client.\n\n#### Constructor\n\n```python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    received: Optional[queue.Queue[bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop: Optional[Callable[[], bool]] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n```\n\n- `address`: A tuple representing the IP address and port number to bind the server to.\n- `received`: Optional queue to store received messages.\n- `reconnect`: If True, the server will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop`: A function that returns True to signal the server to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging server events.\n\n#### Properties\n- `ip`: The IP address component of the server's address.\n- `port`: The port number component of the server's address.\n- `received`: The queue containing received messages.\n\n#### Methods\n- `listen()`: Creates the socket and puts it in listen mode.\n- `accept_connection()`: Accepts a new connection.\n- `start()`: Starts the server in a new thread.\n- `join()`: Waits for the server thread to finish.\n- `shutdown()`: Signals the server to shut down gracefully.\n- `close_connection()`: Closes the client connection and the socket.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point. Closes all sockets\n\n### ServerSender\n\n#### Constructor\n\n```python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    to_send: Optional[queue.Queue[str | bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop: Optional[Callable[[], bool]] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n```\n\n- `address`: A tuple representing the IP address and port number to bind the server to.\n- `to_send`: Optional queue to store messages that will be sent.\n- `reconnect`: If True, the server will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop`: A function that returns True to signal the server to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging server events.\n\n#### Properties\n- `ip`: The IP address component of the server's address.\n- `port`: The port number component of the server's address.\n- `to_send`: The queue containing messages to be sent.\n\n#### Methods\n- `listen()`: Creates the socket and puts it in listen mode.\n- `accept_connection()`: Accepts a new connection.\n- `start()`: Starts the server in a new thread.\n- `join()`: Waits for the server thread to finish.\n- `shutdown()`: Signals the server to shut down gracefully.\n- `close_connection()`: Closes the client connection and the socket.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point. Closes all sockets\n\n### Server\n\nA server that sends and receives messages to and from a single client.\nThis server runs in two threads, one to send messages and another to receive messages.\n\n```Python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    received: Optional[queue.Queue[bytes]] = None,\n    to_send: Optional[queue.Queue[str | bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop_receive: Optional[Callable[[], bool]] = None,\n    stop_send: Optional[Callable[[], bool]] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n\n```\n\n- `address`: A tuple representing the IP address and port number to bind the server to.\n- `received`: Optional queue to store received messages.\n- `to_send`: Optional queue containing messages to be sent.\n- `reconnect`: If True, the server will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop_receive`:  A function that returns True to signal the receiving loop to stop.\n- `stop_send`:  A function that returns True to signal the sending loop to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging server events.\n\n#### Properties\n- `received`: The queue containing received messages.\n- `to_send`: The queue containing messages to be sent.\n- `send_thread`: The thread responsible for sending messages.\n- `receive_thread`: The thread responsible for receiving messages.\n\n#### Methods\n- `listen()`: Creates the socket and puts it in listen mode.\n- `accept_connection()`: Accepts a new connection.\n- `start()`: Starts the server in a new thread.\n- `join()`: Waits for both the sending and receiving threads to stop.\n- `shutdown()`: Signals the server to shut down gracefully.\n- `close_connection()`: Closes the client connection and the socket.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point. Closes all sockets\n\n### ClientReceiver\n\nA client that receives messages from a server.\n\n#### Constructor\n\n```python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    received: Optional[queue.Queue[bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop: Optional[Callable[[], bool]] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n```\n\n- `address`: A tuple representing the IP address and port number to connect to.\n- `received`: Optional queue to store received messages.\n- `reconnect`: If True, the client will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop`: A function that returns True to signal the client to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging client events.\n\n#### Properties\n\n- `ip`: The IP address component of the client's address.\n- `port`: The port number component of the client's address.\n- `received`: The queue containing received messages.\n\n#### Methods\n- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.\n- `start()`: Starts the client in a new thread.\n- `join()`: Waits for the client thread to finish.\n- `shutdown()`: Signals the client to shut down gracefully.\n- `close_connection()`: Closes the socket connection.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point.\n\n### ClientSender\n\n```python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    to_send: Optional[queue.Queue[bytes | bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop: Optional[Callable[[], bool]] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n```\n\n- `address`: A tuple representing the IP address and port number to connect to.\n- `to_send`: Optional queue to store messages to be sent.\n- `reconnect`: If True, the client will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop`: A function that returns True to signal the client to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging client events.\n\n#### Properties\n\n- `ip`: The IP address component of the client's address.\n- `port`: The port number component of the client's address.\n- `to_send`: The queue containing messages to be sent.\n\n#### Methods\n- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.\n- `start()`: Starts the client in a new thread.\n- `join()`: Waits for the client thread to finish.\n- `shutdown()`: Signals the client to shut down gracefully.\n- `close_connection()`: Closes the socket connection.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point.\n\n### Client\n\nA client that sends and receives messages to and from a server.\n\n```python\ndef __init__(\n    self,\n    address: tuple[str, int],\n    received: Optional[queue.Queue[bytes]] = None,\n    to_send: Optional[queue.Queue[str | bytes]] = None,\n    reconnect: bool = True,\n    timeout: Optional[float] = None,\n    stop_receive: Callable[[], bool] = None,\n    stop_send: Callable[[], bool] = None,\n    stop_reconnect: Optional[Callable[[], bool]] = None,\n    logger: Optional[logging.Logger] = None,\n)\n```\n- `address`: A tuple representing the IP address and port number to connect to.\n- `received`: Optional queue to store received messages.\n- `to_send`: Optional queue containing messages to be sent.\n- `reconnect`: If True, the client will attempt to reconnect after disconnection.\n- `timeout`: Optional timeout value for send and receive operations.\n- `stop_receive`: A function that returns True to signal the receiving loop to stop.\n- `stop_send`: A function that returns True to signal the sending loop to stop.\n- `stop_reconnect`: A function that returns True to signal the reconnecting loop to stop. Won't have\nany effect if reconnect is set to False.\n- `logger`: Optional logger for logging client events.\n\n#### Properties\n\n- `ip`: The IP address component of the client's address.\n- `port`: The port number component of the client's address.\n- `received`: The queue containing received messages.\n- `to_send`: The queue containing messages to be sent.\n- `send_thread`: The thread responsible for sending messages.\n- `receive_thread`: The thread responsible for receiving messages.\n\n#### Methods\n- `connect(timeout: Optional[float] = None)`: Connects to the server with an optional timeout.\n- `start()`: Starts the client in a new thread.\n- `join()`: Waits for the client thread to finish.\n- `shutdown()`: Signals the client to shut down gracefully.\n- `close_connection()`: Closes the socket connection.\n- `__enter__()`: Context manager entry point.\n- `__exit__(...)`: Context manager exit point.\n\n\n### AbstractService\n\nThis abstract base class is a blueprint  to easily create other services that communicate with each other trough queues. Very useful\nfor processing, storing, etc. the data received trough sockets.\n\nAbstract base class for all services.\n\nTo add a new service, implement the `_handle_message` method.\n\nA service consists of an input queue and an output queue. The purpose of a service is to apply some function to the inputs to obtain the outputs that can then be processed by another service or sent to a receptor.\n\nMost services are meant to run indefinitely, and so they do not run in the main thread. However, a custom function to terminate the service when needed can be used, and the service can also run in the main thread if necessary.\n\n#### Constructor\n\n```python\ndef __init__(\n            self,\n            in_queue: Optional[queue.Queue] = None,\n            out_queue: Optional[queue.Queue] = None,\n            stop: Optional[Callable[[], bool]] = None,\n            events: Optional[dict[str, threading.Event]] = None,\n            logger: Optional[logging.Logger] = None,\n    ):\n```\n\n#### Parameters:\n\n- `in_queue` (Optional[queue.Queue]): Input queue for receiving messages.\n- `out_queue` (Optional[queue.Queue]): Output queue for sending messages.\n- `stop` (Optional[Callable[[], bool]]): Custom stop function.\n- `events` (Optional[dict[str, threading.Event]]): Dictionary of events.\n- `logger` (Optional[logging.Logger]): Logger for logging events.\n\n### Examples \n\nSample usage of a client that sends receives data from a server. The `client.py` program\nwill use a custom `MessageLogger` service to log all the data it receives, while the\n`server.py` program whill use a service `MessageGenerator`to generate messages continuously\nand send them to the client.\n\n```python\n# client.py\nfrom socketlib import ClientReceiver\nfrom socketlib.services.samples import MessageLogger\nfrom socketlib.utils.logger import get_module_logger\n\nif __name__ == \"__main__\":\n\n    address = (\"localhost\", 12345)\n    client = ClientReceiver(address, reconnect=True)\n    \n    logger = get_module_logger(__name__, \"dev\")\n    msg_logger = MessageLogger(client.received, logger)\n    \n    with client:\n        client.connect()\n        client.start()\n        msg_logger.start()\n        \n        try:\n            client.join()\n        except KeyboardInterrupt:\n            client.shutdown()\n            msg_logger.shutdown()\n\n```\n\n```python\n# server.py\nfrom socketlib import ServerSender, get_module_logger\nfrom socketlib.services.samples import MessageGenerator\n\n\nif __name__ == \"__main__\":\n\n    address = (\"localhost\", 12345)\n    server = ServerSender(address)\n    \n    logger = get_module_logger(__name__, \"dev\", use_file_handler=False)\n    msg_gen = MessageGenerator(server.to_send, logger)\n    \n    with server:\n        server.start()\n        msg_gen.start()\n        \n        try:\n            server.join()\n        except KeyboardInterrupt:\n            server.shutdown()\n            msg_gen.shutdown()\n\n```\n\n## Developing\n\nDeveloped in Python 3.11.4\n\nInstalling the development environment:\n\n```shell\ngit clone https://github.com/Daniel-Ibarrola/MServ\npython3.11 -m venv venv\nsource venv/bin/activate\npip install -r requirements/dev.txt\npip install -e .\n```\n\n## License\n\n`pysocklib` was created by Daniel Ibarrola. It is licensed under the terms\nof the MIT license.\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 Daniel Ibarrola S\u00e1nchez  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "summary": "Library to work with socket clients and servers.",
    "version": "0.6.1",
    "project_urls": {
        "Homepage": "https://github.com/Daniel-Ibarrola/SocketLib.git"
    },
    "split_keywords": [
        "socket",
        "client",
        "server"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "303c634c3e5277fb9cadab24bda321133458c5ba2cbc3aa145ae68434884c9df",
                "md5": "dc429959d16f8f405646b86409f840a9",
                "sha256": "540e01c910500bdeeb5d117d06e981723d549858db601e49f32b9b50d955772d"
            },
            "downloads": -1,
            "filename": "pysocklib-0.6.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "dc429959d16f8f405646b86409f840a9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 20374,
            "upload_time": "2023-12-11T21:09:23",
            "upload_time_iso_8601": "2023-12-11T21:09:23.648114Z",
            "url": "https://files.pythonhosted.org/packages/30/3c/634c3e5277fb9cadab24bda321133458c5ba2cbc3aa145ae68434884c9df/pysocklib-0.6.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "53343d6c5c354d2e0cffc3205538fd0d03decbcfed8c974eff738c10c8fa75f8",
                "md5": "9de68b8a0244792dcd08a315ee598d95",
                "sha256": "a5dffd36aa322f3dbdc8be29e106df9d791aefd497194f7f4ede5c465cbf8f89"
            },
            "downloads": -1,
            "filename": "pysocklib-0.6.1.tar.gz",
            "has_sig": false,
            "md5_digest": "9de68b8a0244792dcd08a315ee598d95",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 15022,
            "upload_time": "2023-12-11T21:09:25",
            "upload_time_iso_8601": "2023-12-11T21:09:25.353906Z",
            "url": "https://files.pythonhosted.org/packages/53/34/3d6c5c354d2e0cffc3205538fd0d03decbcfed8c974eff738c10c8fa75f8/pysocklib-0.6.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-11 21:09:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Daniel-Ibarrola",
    "github_project": "SocketLib",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pysocklib"
}
        
Elapsed time: 3.00849s