How do I force the server to receive messages from the client and display the message: "{name} send message: {data}"? For example, a user sends a message to another user, and when a user named John sends the message "Hello Alice, how are you?", The server will be displayed at this point - John will send a message: Hello Alice, how are you? I will be grateful for your help. I hope will find the answer to this question in this article. Code below:
server:
import threading
import socket
HOST = '127.0.0.1'
PORT = 8888
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(15)
print(f'Server {HOST}:{PORT} start.')
users = []
def send_all(data):
for user in users:
user.send(data)
def listen_user(user):
print('Listening user')
while True:
data = user.recv(1024)
print(f'User sent {data}')
send_all(data)
def start_server():
while True:
user_socket, addr = server.accept()
users.append(user_socket)
potok_info = threading.Thread(target=listen_user, args=(user_socket,))
potok_info.start()
if __name__ == '__main__':
start_server()
client:
import socket
import time
import threading
import os
HOST = '127.0.0.1'
PORT = 8888
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
def send_message():
print('Enter name: ')
name = input()
while True:
data = client.recv(1024)
print(data.decode('utf-8'))
msg = (f'{name} send message {data}')
client.send(msg.encode('utf-8')) # this
def send_server():
listen_thread = threading.Thread(target=send_message)
listen_thread.start()
while True:
client.send(input('you: ').encode('utf-8'))
if __name__ == '__main__':
os.system('clear')
print('***** Welcome in Security Chat. *****')
send_server()