'How to listen and connect multiple ports with python?
I'm working on a program that's basicly sending/recieving messages but I want to make a ranking system. The admins of this program can inform each other as well as the other users. I read so many articles already but I can't find the solution. Can anyone help me? Here is the code for the server:
import socket,threading
HOST='127.0.0.1'
PORT=9134
PORT2=2233
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.bind((HOST,PORT2))
server.listen()
clients=[]
nicknames=[]
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while 1:
try:
message = client.recv(1024)
print(f'{message}')
broadcast(message)
except:
index=clients.index(client)
clients.remove(client)
client.close()
nickname=nicknames[index]
nicknames.remove(nickname)
break
def receive():
while 1:
client, adress=server.accept()
print(f'Connected with {str(adress)}')
client.send("NICK".encode('utf-8'))
nickname=client.recv(1024)
nicknames.append(nickname)
clients.append(client)
broadcast(f'{nickname} connected to the server!\n'.encode('utf-8'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print(clients,nicknames)
print("Server is running")
receive()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
