From 00c94b91a3b6b8ecf2b61ca8a2bd1eceb9c423e5 Mon Sep 17 00:00:00 2001 From: Giles Knap Date: Wed, 31 Aug 2022 14:44:27 +0100 Subject: [PATCH] make communicate functions thread safe --- rcon/battleye/client.py | 10 ++++++---- rcon/source/client.py | 9 ++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/rcon/battleye/client.py b/rcon/battleye/client.py index 2f710c9..5e4f1c6 100644 --- a/rcon/battleye/client.py +++ b/rcon/battleye/client.py @@ -2,6 +2,7 @@ from logging import getLogger from socket import SOCK_DGRAM +from threading import Lock from typing import Callable from rcon.battleye.proto import RESPONSE_TYPES @@ -17,7 +18,7 @@ from rcon.exceptions import WrongPassword __all__ = ['Client'] - +lock = Lock() MessageHandler = Callable[[ServerMessage], None] @@ -55,10 +56,11 @@ class Client(BaseClient, socket_type=SOCK_DGRAM): def communicate(self, request: Request) -> Response: """Send a request and receive a response.""" - with self._socket.makefile('wb') as file: - file.write(bytes(request)) + with lock: + with self._socket.makefile('wb') as file: + file.write(bytes(request)) - return self.receive() + return self.receive() def login(self, passwd: str) -> bool: """Log-in the user.""" diff --git a/rcon/source/client.py b/rcon/source/client.py index 47de7e0..4049c1f 100644 --- a/rcon/source/client.py +++ b/rcon/source/client.py @@ -1,14 +1,16 @@ """Synchronous client.""" from socket import SOCK_STREAM +from threading import Lock from rcon.client import BaseClient from rcon.exceptions import SessionTimeout, WrongPassword from rcon.source.proto import Packet, Type - __all__ = ['Client'] +lock = Lock() + class Client(BaseClient, socket_type=SOCK_STREAM): """An RCON client.""" @@ -31,8 +33,9 @@ class Client(BaseClient, socket_type=SOCK_STREAM): def communicate(self, packet: Packet) -> Packet: """Send and receive a packet.""" - self.send(packet) - return self.read() + with lock: + self.send(packet) + return self.read() def send(self, packet: Packet) -> None: """Send a packet to the server."""