Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.4 kB
1
Indexable
Never
import socket
import threading

server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# piece of code to allow IP address & Port
host="0.0.0.0"
port=8548
server.bind((host,port))
server.listen(5)

clients = []
nicknames = []

def broadcast(message):
    for client in clients:
        client. send(message)

def handle(client):
    while True:
        try:
            message = client.recv(1024)
            print(f"{nicknames[clients.index(client)]} says {message}")
            broadcast(message)
        except:
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            nicknames.remove(nickname)
            break

def receive():
    while True:
        client, address = server.accept()
        print()

        client.send("NICK". encode('utf-8'))
        nickname = client.recv(1024).decode()
        nicknames.append(nickname)
        clients.append(client)
        print(f"Nickname of the client is {nickname}")
        broadcast(f"{nickname} connected to the server!\n".encode('utf-8'))
        client.send("connected to the server".encode())

        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

print("server is running..")
receive()