Answer the question
In order to leave comments, you need to log in
How can I make the messages printed by one client in python chat be received not only by the server, but also by other clients?
here is the server code:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', 9090 ))
print('Server > local host')
clients = []
while True:
data, addr = server_socket.recvfrom(1024)
if addr not in clients:
clients.append(addr)
print(data.decode('utf-8'))
for client in clients:
server_socket.sendto(data, client)
server_socket.close()
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.connect(('localhost', 9090))
server = ('localhost', 9090)
config = input('please enter your name: ')
client_socket.sendto(("["+config + "] => join chat ").encode("utf-8"),server)
i = False
while i == False:
message = input(':')
client_socket.sendto(('['+config + ']' + ':' + message).encode('utf-8'), server)
while True:
data = client_socket.recv(1024)
print(data.decode('utf-8'))
if not data:
break
client_socket.close()
Answer the question
In order to leave comments, you need to log in
.recv - accepted, .send - sent.
Don't forget to use .encode().
And other users can be stored somewhere.
For example, in a dictionary. So it can be divided into rooms.
Like this when connected:
myUsers = {}
client_address, client_socket = server.accept()
myUsers.update({len(myUsers): client_socket})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question