Last active
February 15, 2020 20:31
-
-
Save ceffiong/d8ce75f45f11e5e361b759a8cbab8804 to your computer and use it in GitHub Desktop.
Multi-user Group Chat Server function to send and receive clients messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### several lines of codes ommitted | |
### See https://gist.github.com/effiongcharles/4976708e0791cfc959953743e4650b5e.js for preceeing codes | |
# Function to receive message from current client AND | |
# Send that message to other clients | |
def send_receive_client_message(client_connection, client_ip_addr): | |
global server, client_name, clients, clients_addr | |
client_msg = " " | |
# send welcome message to client | |
client_name = client_connection.recv(4096) | |
client_connection.send("Welcome " + client_name + ". Use 'exit' to quit") | |
clients_names.append(client_name) | |
update_client_names_display(clients_names) # update client names display | |
while True: | |
data = client_connection.recv(4096) | |
if not data: break | |
if data == "exit": break | |
client_msg = data | |
idx = get_client_index(clients, client_connection) | |
sending_client_name = clients_names[idx] | |
for c in clients: | |
if c != client_connection: | |
c.send(sending_client_name + "->" + client_msg) | |
# find the client index then remove from both lists(client name list and connection list) | |
idx = get_client_index(clients, client_connection) | |
del clients_names[idx] | |
del clients[idx] | |
client_connection.close() | |
update_client_names_display(clients_names) # update client names display | |
# Helper function to return the index of the current client in the list of clients | |
def get_client_index(client_list, curr_client): | |
idx = 0 | |
for conn in client_list: | |
if conn == curr_client: | |
break | |
idx = idx + 1 | |
return idx | |
# Helper function to Update client name display when a new client connects OR | |
# When a connected client disconnects | |
def update_client_names_display(name_list): | |
tkDisplay.config(state=tk.NORMAL) | |
tkDisplay.delete('1.0', tk.END) | |
for c in name_list: | |
tkDisplay.insert(tk.END, c+"\n") | |
tkDisplay.config(state=tk.DISABLED) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment