F
F
Freiz Belfast2018-07-20 18:53:36
Python
Freiz Belfast, 2018-07-20 18:53:36

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()

here is the client code
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

1 answer(s)
S
Sergey Grigorov, 2018-07-21
@oneiromant

.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})

This will allow you to store the connections of all users and work with anyone in any place, incl. calling send
I also advise you not to use .recv(1024), but just send the length of the received message at the beginning, as a header.
Thus, you will be able to receive Messages up to 4 with something billion characters long.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question