My python chat server does not send messages properly

When sending a message for the send time from the client it is not sent to the other client.

I’m fairly new to Python and sockets. some of the commented off code has been code I’ve tried but has not worked.

My server code:

import socket
import threading

def handle_client(client_socket):
    while True:
        data = client_socket.recv(1024)
        if not data:
            break
        message = data.decode('utf-8')
        message = str(message)

        for i in clients:
            i.send(message.encode('utf-8'))
            # i.sendall(message.encode('utf-8'))
            #i = 0
            
    
        print(f"Received message: {message}")
        #response = "Server received your message: " + message
        #client_socket.sendall(response.encode('utf-8'))
    # client_socket.close()

def main():
    global clients
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    server_socket.bind((host, port))
    # server_socket.listen()
    print(f"Server listening on {host}:{port}")
    clients = []
    names = []

    while True:
        server_socket.listen()
        client_socket, client_address = server_socket.accept()
        Username = client_socket.recv(1024).decode('utf-8')
        names.append(Username)
        clients.append(client_socket)
        print(f"Accepted connection from {client_address} with name {Username}")
        # print(f"CLIENT SOCKET: {client_socket}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()

if __name__ == "__main__":
main()

My client code:

import socket
import threading

def recive():
    data = client_socket.recv(1024)
    msg = data.decode('utf-8')
    print(f"{msg}")

def main():
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    Username = input('Username: ')
    client_socket.connect((host, port))
    client_socket.sendall(Username.encode('utf-8'))
    recive_handler = threading.Thread(target=recive)
    recive_handler.start()

    while True:
        message = input("Enter your message: ")
        client_socket.sendall(message.encode('utf-8'))

if __name__ == "__main__":
    main()

I’ve tried changing sendall() to send(),
resetting I in the for loop, and removing client_socket.close()

New contributor

BoneheadBreaker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

In your server code, it is not safe when multiple clients connect to the server, and when an error occurs the code will crash.

  • It’s necessary to add a lock when adding the client to the clients list.
  • It’s necessary to add the try-except block check.

I have tested the following codes successfuly.

The socket server code:

import socket
import threading

clients = []
clients_lock = threading.Lock()

def handle_client(client_socket, client_address):
    while True:
        try:
            data = client_socket.recv(1024)
            if not data:
                break

            message = data.decode('utf-8')
            print(f"Received message from {client_address}: {message}")

            # Broadcast message to all clients
            with clients_lock:
                for client in clients:
                    if client != client_socket:
                        client.sendall(message.encode('utf-8'))
        except ConnectionResetError:
            break

    with clients_lock:
        clients.remove(client_socket)
    client_socket.close()
    print(f"Connection closed from {client_address}")

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    server_socket.bind((host, port))
    server_socket.listen()
    print(f"Server listening on {host}:{port}")

    while True:
        client_socket, client_address = server_socket.accept()
        print(f"Accepted connection from {client_address}")

        with clients_lock:
            clients.append(client_socket)

        client_handler = threading.Thread(target=handle_client, args=(client_socket, client_address))
        client_handler.start()

if __name__ == "__main__":
    main()

The socket client code:

import socket
import threading

def receive():
    while True:
        try:
            data = client_socket.recv(1024)
            if data:
                msg = data.decode('utf-8')
                print(f"Received data: {msg}")
            else:
                break
        except ConnectionResetError:
            break

def main():
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    client_socket.connect((host, port))

    username = input('Username: ')
    client_socket.sendall(username.encode('utf-8'))

    receive_handler = threading.Thread(target=receive)
    receive_handler.start()

    while True:
        message = input("Enter your message: ")
        if message:
            client_socket.sendall(message.encode('utf-8'))

if __name__ == "__main__":
    main()

New contributor

Hui Xiao is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật