Reputation: 63
I have wrote a server for receiving multiple clients and it can communicate to the clients separately. Here i can list the connected clients in the server, but it doesn't remove the clients from the server when the client is disconnected.
Server.py
import socket
from threading import Thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '0.0.0.0'
port = 4141
s.bind((ip, port))
s.listen(5)
connected_clients=[]
def handle_client(c, addr):
while True:
try:
message = input("You: ")
message = message.encode("ascii")
c.send(message)
except:
print("Disconnected for sending..")
reply = c.recv(4141)
if not reply:
print("Disconnected for receiving..")
else:
reply = reply.decode('ascii')
print("Other : ", reply)
while True:
c, addr = s.accept()
# print('Connected:', addr)
connected_clients.append(addr[0])
print(connected_clients)
t = Thread(target=handle_client, args=(c, addr))
t.setDaemon(True)
t.start()
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 4141
ip = input('Enter the IP Address::')
s.connect((ip, port))
while True:
message = input("You: ")
message = message.encode("ascii")
s.send(message)
reply = s.recv(4141)
reply = reply.decode('ascii')
print("Other : ", reply)
s.close()
1) list the connected clients in the server and other clients(every clients need to list which all are the clients are currently active in the server)
2) Also have to remove the clients when it is disconnected from the server, this updated connected clients information have to be passed into all currently connected clients.
I have research through the following answers, but its not working out.
Upvotes: 2
Views: 5534
Reputation: 11
Hope this can help you:
def check_connections(self):
""" Check if the client(s) are/is still connected """
for i, connection in enumerate(self.all_connections):
try:
connection.send(b'PING')
data = connection.recv(1024)
if len(data) == 0:
del self.all_connections[i]
del self.all_addresses[i]
except ConnectionError:
del self.all_connections[i]
del self.all_addresses[i]
This a function for check connection, the client must answer something(for me PING) if he does not answer, that mean it is disconnected, so we remove it from the list.For me, that's work,you just need to update the list often with this function.
Upvotes: 1
Reputation: 108
I'm not that much into server development, but this might help:
for client in connected_clients:
connected=str(connected_clients)
s.send(connected.encode())
This can be done on request, like:
data = s.recv(1024)
if data == <command name here as string>:
#Call the code above.
For deleting inactive users, you can do:
whoLeft = s.recv(1024)
if whoLeft in connected_clients:
connected_clients.remove(whoLeft)
You will have to adjust the client so that before disconnecting it sends its address, but otherwise this should be fine.
Upvotes: 1