1

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()
Sap2ch
  • 27
  • 6
  • The server needs to decode `data`. – Barmar Oct 25 '21 at 17:28
  • Does this answer your question? [How to send a message from client to server in python](https://stackoverflow.com/questions/37227176/how-to-send-a-message-from-client-to-server-in-python) – gawkface Oct 27 '21 at 04:17

1 Answers1

0

I modified your code like that.

This is your server script.

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 = [] # To store their name
sort = [] # To store their socket

def listen_user(user):
    print('Listening user')
    sort.append(user)  # Store their socket in sort[]
    user.send('Name'.encode('utf-8')) # send 'Name' to clients
    name = user.recv(1024).decode('utf-8') # Receive their name
    users.append(name) # Store their name in user[]

    while True:
        data = user.recv(1024).decode('utf-8')
        print(f'{name} sent {data}')

        for i in sort: # Send received messages to clients
           if(i != server and i != user): # Filter server and message sender. Send message except them.
               i.sendall(f'{name} > {data}'.encode('utf-8'))
   
    user.close() # To close client socket connection.

def start_server():
    while True:
       user_socket, addr = server.accept()
       potok_info = threading.Thread(target=listen_user, args=(user_socket, ))
       potok_info.start()


if __name__ == '__main__':
    start_server()

And This is your client script,

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

   if('Name' in client.recv(1024).decode('utf-8')): # If 'Name' received. It allows you to send the name.
       name  = input('Enter Name : ') # Type name
       client.send(name.encode('utf-8'))

   while True:
       data = input('Enter : ') # Enter message
       client.send(data.encode('utf-8'))
    
       receive = client.recv(1024).decode('utf-8')# Receive messages from other clients.
       print(receive)

def send_server():

   listen_thread = threading.Thread(target=send_message)
   listen_thread.start()      

if __name__ == '__main__':
   os.system('clear')
   print('***** Welcome in Security Chat. *****')
   send_server()

Add remove some part in your code. Study it carefully then you can identify errors in your code.

  • Thank you very much for the changed code, it really improved. But see how to get the server to receive messages from the client and display it on the server? Required settings: the user enters a name in the client, when sending a message to another client, the server will display his name and the information he sends. – Sap2ch Oct 25 '21 at 20:09
  • What do you mean?, I think you want to display clients name and their messages in server side too. – Vinura Yashohara Oct 25 '21 at 20:13
  • I change my code try it out. Tell me if you want to change something else. – Vinura Yashohara Oct 25 '21 at 20:22
  • Yes, I would like to display messages in parallel on a server with a specific name, who does it. For example, I started a server and two clients. I named the first John, the second Jessica. John sends a message to the second client (Jessica), and after successfully sending it, Jessica receives a message from John, and the server receives the message and the name of the client who sent it. – Sap2ch Oct 25 '21 at 21:12
  • I think we need to take the variable "name" via input () and pass this variable to the client on the server via client.send (name.encode ('utf-8)), but this option is incorrect, although the logic is clear. - print (f '{name} send the following message: {data}'. – Sap2ch Oct 25 '21 at 21:12
  • I think you want to display a message in server like that, eg:- John and Jessica message with together. The server displays a message like that -- 'John sends a message to Jessica', after receiving Jessica's message by John, the server shows 'Jessica sends a message to John'. – Vinura Yashohara Oct 26 '21 at 01:34
  • Yes, we can try this way, but then how to transfer username information to the server? What do you recommend changing in the code itself? – Sap2ch Oct 26 '21 at 08:46
  • I used this way to transfer username to the server. First Server sends 'Name' to the clients. In client-side script search 'Name' in server messages, if 'Name' word found then it says User to enter the name. After that client sends User's name to the server and server store user name in a User list. – Vinura Yashohara Oct 26 '21 at 12:09
  • I commented these instructions in my code look at it. Then you can identify what it is. – Vinura Yashohara Oct 26 '21 at 12:14
  • Friend, I fixed everything in the code and really get the desired result. I am very grateful for your help, can I help you in any way? For example, to leave somewhere a positive response about you? – Sap2ch Oct 26 '21 at 13:19
  • I'm glad to help you. If my answer is helpful, you can vote it or select it as an answer. – Vinura Yashohara Oct 26 '21 at 14:35