i have a code which needs to perform the task of sending and receiving messages from specific clients. When i mention the client address in the send function of the server, i am being given a key error.
[NEW CONNECTION] ('10.14.0.1', 52870) connected.[ACTIVE CONNECTIONS] 1
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\sho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
self.run()
File "c:\Users\sho\Documents\TcpCommExample\Server and clients\server 5.py", line 33, in run
clients["10.14.0.1"].send("VITA".encode(FORMAT))
KeyError: '10.14.0.1'
I have checked the dictionary by printing it and the client address does exist in it, i am not sure where i am making a mistake. Here is the code and any help would be tremendously appreciated.
import socket, threading
import time
HEADER = 80
PORT = 9000
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
VITA_POSITIVE = "0000"
my_timer = 0
class ClientThread(threading.Thread):
def __init__(self, conn: socket.socket, addr: str):
threading.Thread.__init__(self)
self.conn = conn
self.addr = addr
def send(self, msg: str):
self.conn.sendall(msg.encode())
def run(self):
print(f"[NEW CONNECTION] {self.addr} connected.")
connected = True
while connected:
clients["10.14.0.1"].send("VITA".encode(FORMAT))
vita_response_iconet = clients["10.14.0.1"].recv(HEADER).decode(FORMAT)
print(vita_response_iconet)
if vita_response_iconet == VITA_POSITIVE:
print("VITA received from Iconet")
vita_iconet = 1
else:
print("VITA not received from Iconet")
vita_iconet = 0
clients["10.14.0.1"].send("VITA".encode(FORMAT))
vita_response_robot = clients["10.14.0.1"].recv(HEADER).decode(FORMAT)
print(vita_response_robot)
if vita_response_iconet == VITA_POSITIVE:
print("VITA received from Robot")
vita_robot = 1
else:
print("VITA not received from Robot")
vita_robot = 0
if vita_iconet and vita_robot == 1:
my_timer = 0
else:
my_timer = my_timer
self.conn.close()
def countup():
global my_timer
for x in range(1, my_timer+1):
time.sleep(1)
countup_thread = threading.Thread(target=countup)
countup_thread.start()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
print('interesting')
print(conn)
print(addr)
thread = ClientThread(conn, addr)
print ('be ready')
thread.start()
clients[addr] = thread
print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 2}")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
clients = {}
connections = threading.Thread(target=start)
connections.start()
print("[STARTING] server is starting...")
start()