-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient1.py
85 lines (74 loc) · 3.17 KB
/
client1.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
import asyncio
import websockets
import logging
import time
from time import sleep
import datetime
connected = True
#Changing the configuration of logging
logging.basicConfig(
filename="data1.txt",
filemode='w',
format="%(message)s",
level=logging.INFO,
)
async def client():
async with websockets.connect("ws://localhost:8000") as websocket:
# Create tasks to send and receive messages concurrently
send_task = asyncio.create_task(send_messages(websocket))
receive_task = asyncio.create_task(receive_messages(websocket))
await asyncio.gather(send_task, receive_task)
async def send_messages(websocket):
await websocket.send("Connected with client-1")
async def receive_messages(websocket):
# Creating an empty dictionary to store the value of data of each block temporarily.
dic = {}
numbering = 0
blockno = 0
blocksize = 3 # Setting the block size as 3
while True:
# Using Error handling
try:
if numbering != blocksize :
ts = time.time()
current_time = datetime.datetime.now()
message = await websocket.recv()
message2 = await websocket.recv()
message3 = await websocket.recv()
message4 = await websocket.recv()
message5 = await websocket.recv()
message6 = await websocket.recv()
message7 = await websocket.recv()
message8 = await websocket.recv()
dic[ts] = f"{current_time} : {message}"
numbering += 1
if numbering == blocksize :
numbering = 0
blockno += 1
for j in dic :
t = j
break
tt = ts - t
# Logging the messages to the text file
logging.info(f'\n Block {blockno} received in time {tt} sec\n')
print(f"Block {blockno} received from server successfully")
await websocket.send(f"Client Client-1 received block number {blockno} in time {tt} sec")
for i in dic :
logging.info(f"{dic[i]}")
dic.clear()
except :
connected = False
print( "connection lost... reconnecting" )
while not connected:
# attempt to reconnect, otherwise sleep for 2 seconds
try:
async with websockets.connect("ws://localhost:8000") as websocket:
# Create tasks to send and receive messages concurrently
print( "re-connection successful" )
connected = True
send_task = asyncio.create_task(send_messages(websocket))
receive_task = asyncio.create_task(receive_messages(websocket))
await asyncio.gather(send_task, receive_task)
except :
sleep( 2 )
asyncio.run(client())