https://img.shields.io/pypi/v/pyTCP.svg https://img.shields.io/pypi/pyversions/pyTCP.svg ReadTheDocs Travis Coveralls

pyTCP

A small tcp package to send and receive tcp messages.

Installation

pip install pyTCP

Usage

synchronous:

from pyTCP import EchoServer, TcpClient

echo_server = EchoServer("127.0.0.1", 12345)
echo_server.start_server()
client = TcpClient("127.0.0.1", 12345)
client.connect()

data_to_send = b"Test message"
client.send(data_to_send)
client_received = client.receive()
server_received = echo_server.last_received
assert data_to_send == client_received
assert data_to_send == server_received

# or with a delimiter
data_to_send = b"Test\nmessage"
client.send(data_to_send)
client_received = client.receive_until(delimiter=b'\n')
assert b"Test" == client_received

echo_server.stop_server()
client.close()

async:

import asyncio

from pyTCP import AsyncTcpClient, EchoServer


async def main():
    echo_server = EchoServer("127.0.0.1", 12345)
    echo_server.start_server()
    client = AsyncTcpClient("127.0.0.1", 12345)
    await client.connect()

    data_to_send = b"Test message"
    await client.send(data_to_send)
    data = await client.receive()
    assert data == data_to_send

    echo_server.stop_server()
    client.close()


if __name__ == "__main__":
    asyncio.run(main())

Note

This project has been set up using PyScaffold 3.2.3. For details and usage information on PyScaffold see https://pyscaffold.org/.

Contents

https://img.shields.io/pypi/v/pyTCP.svg https://img.shields.io/pypi/pyversions/pyTCP.svg ReadTheDocs Travis Coveralls

pyTCP

A small tcp package to send and receive tcp messages.

Installation

pip install pyTCP

Usage

synchronous:

from pyTCP import EchoServer, TcpClient

echo_server = EchoServer("127.0.0.1", 12345)
echo_server.start_server()
client = TcpClient("127.0.0.1", 12345)
client.connect()

data_to_send = b"Test message"
client.send(data_to_send)
client_received = client.receive()
server_received = echo_server.last_received
assert data_to_send == client_received
assert data_to_send == server_received

# or with a delimiter
data_to_send = b"Test\nmessage"
client.send(data_to_send)
client_received = client.receive_until(delimiter=b'\n')
assert b"Test" == client_received

echo_server.stop_server()
client.close()

async:

import asyncio

from pyTCP import AsyncTcpClient, EchoServer


async def main():
    echo_server = EchoServer("127.0.0.1", 12345)
    echo_server.start_server()
    client = AsyncTcpClient("127.0.0.1", 12345)
    await client.connect()

    data_to_send = b"Test message"
    await client.send(data_to_send)
    data = await client.receive()
    assert data == data_to_send

    echo_server.stop_server()
    client.close()


if __name__ == "__main__":
    asyncio.run(main())

Note

This project has been set up using PyScaffold 3.2.3. For details and usage information on PyScaffold see https://pyscaffold.org/.

License

The MIT License (MIT)

Copyright (c) 2020 nimpsch

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.

Contributors

Changelog

Version 0.0.1

  • First version

pyTCP

pyTCP package

Submodules
pyTCP.async_client module
class pyTCP.async_client.AsyncTcpClient(host: str = '127.0.0.1', port: int = 8080, auto_reconnect: bool = True)[source]

Bases: object

Asynchronous tcp client

host

The ip address of the tcp server.

Type:str
port

The port of the tcp server.

Type:int
reader

Instance of the StreamReader

Type:obj:
writer

Instance of the StreamWriter

Type:obj:
auto_reconnect

If true, a reconnect will be made on connection loss.

Type:bool
logger

An instance of the logging module.

Type:
obj:
buffer

The split part of the msg which was not returned.

Type:bool, default=True
close()[source]

Closes the socket connection if it open

connect(timeout: float = 10.0)[source]

Tries to connect to the given host. Waits 0.5 seconds until another try will be made.

Parameters:timeout (float, default 10.0) – The maximum time this function will try to connect until a ClientTimeoutError is raised.
Raises:ClientTimeoutError – If no connection could be established in the given time a ClientTimeoutError is raised.
is_connected

Returns True if connected.

Type:bool
receive(bytes_to_receive: int = 4096) → bytes[source]

Receives messages from the socket. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed, otherwise an empty byte string will be returned.

Parameters:bytes_to_receive (int, default 4096) – Reads the number bytes from the socket. Returns fewer bytes than bytes_to_receive if fewer are available.
Returns:The received data from the socket. Or an empty byte string if socket.error is raised.
Return type:bytes
receive_until(bytes_to_receive: int = 4096, delimiter: bytes = '\n', timeout: float = 1.0) → bytes[source]

Receives messages from the socket until the given delimiter is recognized.

The data will be split at the delimiter. The delimiter will be removed from the message and returned. If the received message contains a message after the delimiter, it will be stored in a buffer and prepended to the next message. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed, otherwise an empty byte string will be returned.

Parameters:
  • bytes_to_receive (int, default 4096) – Reads the number bytes from the socket. Returns fewer bytes than bytes_to_receive if fewer are available.
  • delimiter (bytes, default 'n') – Splits the read data at the delimiter
  • timeout (float, default 1.0) – The maximum time this function will wait until a ClientTimeoutError is raised.
Returns:

The received data from the socket. Or an empty byte string if socket.error is raised.

Return type:

bytes

Raises:

ClientTimeoutError – Raises if no data was read or no delimiter was found withing the given time.

send(data: bytes)[source]

Send a message to the socket. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed.

Parameters:data (bytes) – Sends the given bytes to the socket.
pyTCP.client module
class pyTCP.client.TcpClient(host: str = '127.0.0.1', port: int = 8080, auto_reconnect: bool = True)[source]

Bases: object

A tcp client

host

The ip address of the tcp server.

Type:str
port

The port of the tcp server.

Type:int
auto_reconnect

If true, a reconnect will be made on connection loss.

Type:bool
logger

An instance of the logging module.

Type:
obj:
buffer

The split part of the msg which was not returned.

Type:bool, default=True
close()[source]

Closes the socket connection if it open

connect(timeout: float = 10.0)[source]

Tries to connect to the given host. Waits 0.5 seconds until another try will be made.

Parameters:timeout (float, default 10.0) – The maximum time this function will try to connect until a ClientTimeoutError is raised.
Raises:ClientTimeoutError – If no connection could be established in the given time a ClientTimeoutError is raised.
is_connected

Returns True if connected.

Type:bool
receive(bytes_to_receive: int = 4096) → bytes[source]

Receives messages from the socket. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed, otherwise an empty byte string will be returned.

Parameters:bytes_to_receive (int, default 4096) – Reads the number bytes from the socket. Returns fewer bytes than bytes_to_receive if fewer are available.
Returns:The received data from the socket. Or an empty byte string if socket.error is raised.
Return type:bytes
receive_until(bytes_to_receive: int = 4096, delimiter: bytes = '\n', timeout: float = 1.0) → bytes[source]

Receives messages from the socket until the given delimiter is recognized.

The data will be split at the delimiter. The delimiter will be removed from the message and returned. If the received message contains a message after the delimiter, it will be stored in a buffer and prepended to the next message. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed, otherwise an empty byte string will be returned.

bytes_to_receive : int, default 4096
Reads the number bytes from the socket. Returns fewer bytes than bytes_to_receive if fewer are available.
delimiter : bytes, default ‘\n’
Splits the read data at the delimiter
timeout : float, default 1.0
The maximum time this function will wait until a ClientTimeoutError is raised.
bytes
The received data from the socket. Or an empty byte string if socket.error is raised.
ClientTimeoutError
Raises if no data was read or no delimiter was found withing the given time.
send(data: bytes)[source]

Send a message to the socket. If an socket.error is raised and auto_connect is enabled, a reconnect will be executed.

Parameters:data (bytes) – Sends the given bytes to the socket.
pyTCP.client_errors module
exception pyTCP.client_errors.ClientError[source]

Bases: Exception

exception pyTCP.client_errors.ClientProtocolError[source]

Bases: pyTCP.client_errors.ClientError

exception pyTCP.client_errors.ClientSocketError[source]

Bases: pyTCP.client_errors.ClientError

exception pyTCP.client_errors.ClientTimeoutError[source]

Bases: pyTCP.client_errors.ClientError

pyTCP.server module
class pyTCP.server.EchoServer(ip, port, receive_bytes=4096)[source]

Bases: object

last_received

Returns the last received message.

Type:bytes
start_server()[source]

Starts the tcp server.

stop_server()[source]

Stops the tcp server.

class pyTCP.server.ThreadedTCPRequestHandler(request, client_address, server)[source]

Bases: socketserver.BaseRequestHandler

A threaded tcp request handler

handle()[source]

The handle function.

Reads data from the client as long as the server is not requested to close. Sends the read data back to the client and stores it in a queue.

class pyTCP.server.ThreadedTCPServer(server_address, RequestHandlerClass, bind_and_activate=True)[source]

Bases: socketserver.ThreadingMixIn, socketserver.TCPServer

Module contents

Indices and tables