Created
January 15, 2024 14:04
-
-
Save victory-sokolov/42d4ee01f6d98fbe491e2814132b5c75 to your computer and use it in GitHub Desktop.
Python Chat app
This file contains hidden or 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 socket | |
import threading | |
# define the host and port for the chat server | |
HOST = 'localhost' | |
PORT = 12345 | |
# create a new socket for the chat server | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server.bind((HOST, PORT)) | |
server.listen() | |
# create a list to store connected clients | |
clients = [] | |
# define a function to handle incoming messages | |
def handle_message(client, address): | |
while True: | |
# receive the message from the client | |
message = client.recv(1024).decode('utf-8') | |
# broadcast the message to all connected clients | |
for c in clients: | |
c.sendall(f'{address}: {message}'.encode('utf-8')) | |
# run the chat server | |
print(f'Running chat server on {HOST}:{PORT}') | |
while True: | |
# accept incoming connections from clients | |
client, address = server.accept() | |
print(f'New client connected: {address}') | |
# add the new client to the list of connected clients | |
clients.append(client) | |
# start a new thread to handle incoming messages from the client | |
thread = threading.Thread(target=handle_message, args=(client, address)) | |
thread.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment