Created
June 6, 2021 10:46
-
-
Save Yuma-Tsushima07/fcce4f99fe6c91d6eaa1e679236017ea to your computer and use it in GitHub Desktop.
TCP Room
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
import threading | |
import socket | |
alias = input('Choose an alias --> ') | |
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
client.connect(('127.0.0.1', 5000)) | |
def client_receive(): | |
while True: | |
try: | |
message = client.recv(1024).decode('utf-8') | |
if message == "alias?": | |
client.send(alias.encode('utf-8')) | |
else: | |
print(message) | |
except: | |
print('Error!') | |
client.close() | |
break | |
def client_send(): | |
while True: | |
message = f'{alias}: {input("")}' | |
client.send(message.encode('utf-8')) | |
receive_thread = threading.Thread(target=client_receive) | |
receive_thread.start() | |
send_thread = threading.Thread(target=client_send) | |
send_thread.start() |
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
import threading | |
import socket | |
host = '127.0.0.1' | |
port = 5000 | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.bind((host, port)) | |
server.listen() | |
clients = [] | |
aliases = [] | |
def broadcast(message): | |
for client in clients: | |
client.send(message) | |
def handle_client(client): | |
while True: | |
try: | |
message = client.recv(1024) | |
broadcast(message) | |
except: | |
index = clients.index(client) | |
clients.remove(client) | |
client.close() | |
alias = aliases[index] | |
broadcast(f'{alias} has left the chat room!'.encode('utf-8')) | |
aliases.remove(alias) | |
break | |
def receive(): | |
while True: | |
print('Server is running and listening ...') | |
client, address = server.accept() | |
print(f'connection is established with {str(address)}') | |
client.send('alias?'.encode('utf-8')) | |
alias = client.recv(1024) | |
aliases.append(alias) | |
clients.append(client) | |
print(f'The alias of this client is {alias}'.encode('utf-8')) | |
broadcast(f'{alias} has connected to the chat room!'.encode('utf-8')) | |
client.send('You are now connected!'.encode('utf-8')) | |
thread = threading.Thread(target=handle_client, args=(client,)) | |
thread.start() | |
if __name__ == "__main__": | |
receive() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment