Here’s the code I’ve come up with so far:
Thanks. Some comments:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address=(“192.168.1.8”, 22000)
This is a LAN address. So clients could connect from other hosts on your
LAN. So saving just the port number is not precise enough.
If you bind to 127.0.0.1 instead, only local clients can connect.
Alternatively, save the whole address instead of just the port.
connected_clients= #port numbers!!
#msg_count=0
ls_list=
def handle_client(c):
while True:
data=c.recv(1024)
if data.decode()==“quit”:
c.close()
else:
ls_list.append(client_address[1])
if len(ls_list)>5:
del ls_list[0:5]
Why limit the list to 5? In fact, why delete the leading 5?
If you’re concerned about clients disconnecting, why not remove a client
at the end of handle_client? Then you could have your loop exit on EOF
from the client (probably len(data)==0, or “not data” as we tend to
write that). You can use “break” to exit the loop if this happens.
else:
last_sending=sorted(ls_list, reverse=True)[0]
This isn’t the most recent sender, it is the highest numbered port.
for i in connected_clients:
if i is not last_sending:
You want != here, not “is not”. “==” and “!=” test value equality. “is”
and “is not” tend “this is the same object”. Python happens to make
singletons for small integers, so if 5==5 then also “5 is 5”. But for
large integers this isn’t the case, and it is a bad practice anyway. You
can about the value, not whether the same object is used to represent
it. So test the value (“!=”).
while True:
connection, client_address=s.accept()
connected_clients.append(client_address[1])
As mentioned, why not save the whole address instead of just the port?
t=threading.Thread(target=handle_client, args=(connection, ))
t.start()
Superficially fine, if incomplete.
I have some things to consider.
First is that I’m in some way stuck because I have seen videos about the copy module and it’s methods but I don’t have any ideas about how to actually copy the message to the clients which are not last_sending.
Forget the copy module. It is all about copying data structures. “Copy
the message to a client” just means “write the message to the client
socket”.
Then, I’ve figured out why do I need the for loop to determine who’s last_sending but it seems more reasonable to me to use i instead of client_address[1], because that’s something that changes every time and should be an integer, being my port number.
Why do you care who’s last sending? I thought you only cared whether a
client was the “current” client (which just received a message).
Cheers,
Cameron Simpson cs@cskk.id.au