Skip to main content

Build Status Docs Status PyPI Downloads

QtPyNetwork is a small abstraction layer for sending and receiving messages using TCP sockets.

Check out the complete documentation.

Server

Each server has its own balancer.

Servers:

  • TCPServer - listen for TCP connections

Balancers:

  • NoBalancer - sockets are stored in main thread

  • ThreadBalancer - each socket lives in its own thread, which is created dynamically

  • ThreadPoolBalancer - constant amount of threads, new sockets are created in threads with least load

Client

  • TCPClient

  • ThreadedTCPClient

Usage

See examples directory for client and server code samples.

TCP Client

from qtpy.QtWidgets import QApplication
from qtpy.QtCore import QObject, Slot, QCoreApplication, qInstallMessageHandler

import sys
import logging

from QtPyNetwork.client import TCPClient

IP = "127.0.0.1"
PORT = 12500


class Main(QObject):

    def __init__(self):
        super(Main, self).__init__(None)
        self.logger = logging.getLogger(self.__class__.__name__)

        self.client = TCPClient()
        self.client.message.connect(self.on_message)
        self.client.connected.connect(self.on_connected)
        self.client.failed_to_connect.connect(self.on_failed_to_connect)
        self.client.disconnected.connect(self.close)

    @Slot()
    def start(self):
        self.client.start(IP, PORT)

    @Slot(str, int)
    def on_connected(self, ip: str, port: int):
        self.logger.info(f"Connected to {ip}:{port}")
        self.client.write(b"Kick me plz")

    @Slot(bytes)
    def on_message(self, data: bytes):
        self.logger.info(f"Received: {data}")

    @Slot()
    def on_failed_to_connect(self):
        self.logger.error("Failed to connect")

    @Slot()
    def close(self):
        self.client.close()
        QApplication.instance().quit()


if __name__ == '__main__':
    logging.basicConfig(
        level=logging.NOTSET,
        format="%(asctime)s [%(threadName)s] [%(name)s] [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler()])
    logging.getLogger().debug("Logger enabled")

    app = QCoreApplication(sys.argv)
    main = Main()
    main.start()
    sys.exit(app.exec_())

TCPServer + ThreadPoolBalancer

from qtpy.QtWidgets import QApplication
from qtpy.QtCore import QObject, Slot, QCoreApplication

import sys
import logging
import traceback

from QtPyNetwork.server import TCPServer
from QtPyNetwork.balancer import ThreadPoolBalancer
from QtPyNetwork.models import Client

IP = "127.0.0.1"
PORT = 12500


class Main(QObject):

    def __init__(self):
        super(Main, self).__init__(None)
        self.logger = logging.getLogger(self.__class__.__name__)
        # declare server using ThreadPoolBalancer
        self.server = TCPServer(ThreadPoolBalancer(threads=8))
        # connect signals
        self.server.connected.connect(lambda client, ip, port: client.write(b"Some important data"))
        self.server.disconnected.connect(self.on_disconnected)
        self.server.message.connect(self.on_message)

    @Slot()
    def setup(self):
        # start server
        self.server.start(IP, PORT)

    @Slot(Client, bytes)
    def on_message(self, client: Client, message: bytes):
        # this code will be run everyu time client sends data
        self.logger.info("Received {}: {}".format(client.id(), message))
        if message.decode() == "Kick me plz":
            client.disconnect()

    @Slot(Client)
    def on_disconnected(self, client: Client):
        # do some actions when client disconnects form server
        self.logger.info("Disconnected: {}; Connected: {}".format(client.id(), client.is_connected()))
        self.close()

    @Slot()
    def close(self):
        self.server.close()
        while self.server.is_running():
            self.server.wait()
        QApplication.instance().quit()

Metadata

Release files for QtPyNetwork 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for QtPyNetwork 0.7.0
File Size Uploaded
QtPyNetwork-0.7.0.tar.gz 14.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for QtPyNetwork 0.7.0
File Interpreter ABI Platform
QtPyNetwork-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 38.1 kB

Release files / QtPyNetwork-0.7.0.tar.gz

Download URL QtPyNetwork-0.7.0.tar.gz
Size 14.1 kB
Tags Source
SHA-256 checksum
How to use checksums
9197b7da53ba591ac9803cb0abed1533f9fd47bb697130274c53f4da920efa29
BLAKE2b-256 checksum
How to use checksums
909ce914aab9de00e14eb0ed8b6c68029d410be984d264d828c96aff9d63e90e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.9.13

Release files / QtPyNetwork-0.7.0-py3-none-any.whl

Download URL QtPyNetwork-0.7.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6cbf131c6cec3d0643dfad909a1e560673f66cbfa2e3d731b2a47d7a89278647
BLAKE2b-256 checksum
How to use checksums
6854a4a2e0c1431f04c260defe486ca5605c2365171beea2d66365795e626376
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.9.13

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.4

2 release files

0.4.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page