-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket_client.py
168 lines (140 loc) · 5.03 KB
/
socket_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import asyncio
import logging
import sys
import threading
import time
from typing import Dict, List, Optional
import socketio
from chromatrace import LoggingConfig, LoggingSettings
from chromatrace.tracer import trace_id_ctx
from pydantic import BaseModel, Field
logging_config = LoggingConfig(
LoggingSettings(
enable_tracing=True,
file_path="./logs/app-client.log",
enable_file_logging=True,
show_process_id=True,
)
)
trace_id = "123456"
trace_id_ctx.set(f"C-{trace_id}")
class SocketClientConfig(BaseModel):
server_url: str = "http://0.0.0.0:8001"
namespaces: List[str] = ["/"]
headers: Optional[Dict] = Field(default=None)
socketio_path: str = "/socket.io"
auth: Optional[Dict] = Field(default=None)
logger: bool = False
engineio_logger: bool = False
reconnection: bool = True
reconnection_delay: int = 3
reconnection_attempts: int = 10
class SocketClient:
def __init__(
self,
config: SocketClientConfig,
):
self.logger = logging_config.get_logger(self.__class__.__name__)
self.config = config
self.logger.info("Initializing Socket Client to connect to the server.")
self.logger.info(
"Server URL: %s%s", self.config.server_url, self.config.socketio_path
)
self.sio = socketio.AsyncClient(
handle_sigint=True,
logger=self.logger if self.config.logger else False,
engineio_logger=self.logger if self.config.engineio_logger else False,
reconnection=self.config.reconnection,
reconnection_delay=self.config.reconnection_delay,
reconnection_attempts=self.config.reconnection_attempts,
)
self._client_loop = asyncio.new_event_loop()
self.logger.info("Socket Client is initialized.")
def start_background_loop(self, loop: asyncio.AbstractEventLoop) -> None:
asyncio.set_event_loop(loop)
loop.run_forever()
@property
def client_loop(self):
return self._client_loop
async def connect_to_server(self):
try:
self.logger.info("Connecting to the server...")
await self.sio.connect(
self.config.server_url,
headers=self.config.headers,
socketio_path=self.config.socketio_path,
auth=self.config.auth,
namespaces=self.config.namespaces,
)
self.logger.info("Connected to the server successfully.")
except ConnectionError:
self.logger.error("Connection failed.")
await self.sio.wait()
def call_backs(self):
@self.sio.on("connect", namespace="/")
async def connect():
self.logger.info("Connection established to the server with handshake.")
@self.sio.on("disconnect", namespace="/")
def disconnect():
self.logger.info("Server disconnected.")
self.client_loop.stop()
@self.sio.on("message", namespace="/")
async def message(data):
self.logger.info("Message from the server in `message` event: %s", data)
async def run(self):
self.call_backs()
await self.connect_to_server()
def handle_user_input(base_client: SocketClient, logger: logging.Logger):
while True:
if not base_client.sio.connected:
logger.info(
"Client connection with server has been lost, exiting the client..."
)
sys.exit(1)
time.sleep(0.5) # to enhance showcase
user_input = input('Enter a message (or "exit" to quit): ')
try:
if user_input.lower() == "exit":
break
else:
asyncio.run_coroutine_threadsafe(
base_client.sio.emit(
event="message",
data={"message": user_input},
namespace="/",
),
base_client.client_loop,
)
except KeyboardInterrupt:
break
def create_client():
token = "Bearer XXXXXXXXXXX"
config = SocketClientConfig(
headers={
"authorization": token,
"x-trace-id": trace_id,
},
auth={"Authorization": token},
)
base_client = SocketClient(config=config)
# starting the client background loop
th = threading.Thread(
target=base_client.start_background_loop,
args=(base_client.client_loop,),
daemon=True,
)
th.start()
return base_client
def main():
logger = logging_config.get_logger(__name__)
logger.info("Starting client...")
base_client = create_client()
# running the client in the background loop
asyncio.run_coroutine_threadsafe(base_client.run(), base_client.client_loop)
time.sleep(0.5)
logger.info("Ready to check the connection status and sending messages...")
handle_user_input(base_client, logger)
logger.info("Connection is closing...")
base_client.sio.disconnect()
if __name__ == "__main__":
main()