0

I'm making a chatroom in python but I have an issue where if one user is typing and another sends a message it will add that message to the end of the input that the user is typing in here is the code

User code:

import socket
import threading

ADRESS = "10.203.12.205"
PORT = 60000
DATA = ""

user_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def connect(ADRESS, PORT):
    username = input("Username: ")
    user_socket.connect((ADRESS, PORT))
    user_socket.sendall(bytes(username, 'utf-8'))

    listening = threading.Thread(target=receve_message)
    sending = threading.Thread(target=send_message)
    listening.start()
    sending.start()

def send_message():
    while True:
        DATA = input()
        user_socket.sendall(bytes(DATA, 'utf-8'))
        
def receve_message():
    while True:
        DATA = user_socket.recv(1024).decode('utf-8')
        print(DATA)

connect(ADRESS, PORT)

Server code:

import socket
import threading

# Server configuration
HOST = '10.203.12.205'  # Change this to your server IP address
PORT = 60000

# List to store all connected clients
clients = []

def handle_client(client_socket, client_address):
    username = client_socket.recv(1024).decode('utf-8')
    broadcast((username + " has joined"), client_socket, "system")

    while True:
        try:
            # Receive data from the client
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                # Client has disconnected
                print(f"Client {client_address} has disconnected.")
                clients.remove(client_socket)
                client_socket.close()
                break

            # Broadcast the received message to all other clients
            broadcast(data, client_socket, username)

        except ConnectionResetError:
            # Client forcefully disconnected
            print(f"Client {client_address} has forcefully disconnected.")
            clients.remove(client_socket)
            client_socket.close()
            break

def broadcast(message, sender_socket, username):
    # Send the message to all connected clients except the sender
    for client in clients:
        if client != sender_socket:
            client.send((username + ": " + message).encode('utf-8'))

def start_server():
    # Create a socket object
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to a specific address and port
    server_socket.bind((HOST, PORT))

    # Listen for incoming connections
    server_socket.listen(5)
    print("Server started. Listening for connections...")

    while True:
        # Accept a client connection
        client_socket, client_address = server_socket.accept()
        print(f"Client {client_address} connected.")

        # Add the client socket to the list
        clients.append(client_socket)

        # Create a new thread to handle the client
        client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
        client_thread.start()

# Start the server
start_server()

I expected it to print the message before the input it currently does this: Testing image

  • 2
    You’ll need a `curses` package or a GUI like `tkinter` to separate incoming messages from outgoing text. – Mark Tolonen Jun 28 '23 at 01:51
  • 1
    @Luke Cheney – For a `curses` example, see [Simultaneous input and output for network based messaging program](https://stackoverflow.com/a/34992925/2413201). – Armali Jun 28 '23 at 07:44
  • thank you @Armali but it doesn't seem to work for me I've tried looking through the documentation of curses but I'm not able to get it to work – Luke Cheney Jun 28 '23 at 22:42
  • Maybe it would be possible to help if you promulgated what you mean by _it doesn't seem to work for me_. – Armali Jun 29 '23 at 05:03

0 Answers0