Python Server-Client Messaging

21 Views Asked by At

I'm trying to use Python sockets to build a server-client chat system. The problem I'm running into is that no messages are displayed until that machine sends a message itself, then it displays all messages it has received. I am aware that there are other issues in this code, and other pointers are definitely welcome, but I am primarily focused on finding a way to fix this error, as I have had no luck at all with it. My code is below.

Server:

import socket
from threading import *

HOSTNAME = socket.gethostname()
HOST = socket.gethostbyname(HOSTNAME)
PORT = 4141
clients = []
client_num = 0
PORTS_ARRAY = [4141,4142]

print(f"Server {HOST} online")




class Connection():

    def __init__(self):
        self.sock = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
        self.port = PORTS_ARRAY[0]
        PORTS_ARRAY.pop(0)
        print(f"[.] Binding server listener to port {self.port}...")
        self.sock.bind((HOST , self.port))
        print("[.] Listener bind successful! Starting listener service...")
        self.sock.listen()
        self.client = ""
        self.address = ""
        
        while not self.client and not self.address:
            self.client,self.address = self.sock.accept()

        print(f"[+] Client {self.address[0]}:str({self.address[1]}) has connected to server")
        self.client.send(f"[+] Connection request accepted by server {HOST}".encode("utf-8"))
        clients.append([self.address[0],self.address[1]])

    def close_connection(self):

        try:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
        except:
            print(f"[-] Client {self.address} has disconnected")
        PORTS_ARRAY.append(self.port)

    def message_client(self, message):
        self.client.send(f"Message from server {HOST} : {message}".encode("utf-8"))

    def port_listen(self):
                
        while True:
            server_message = input()
            if server_message:
                self.message_client(server_message.encode("utf-8"))
            try:
                message = self.client.recv(4096).decode("utf-8")
            except:
                self.close_connection()

            if message == "/BYE":
                self.close_connection()
                break

            elif message == "/ONLINE":
                print(clients)

            else:
                print(f"[IN] Message from client {self.address[0]}:{self.address[1]}  :  {message}")



client_one = Connection()
c1_listener = Thread(target=client_one.port_listen, daemon=True)
c1_listener.start()

client_two = Connection()
c2_listener = Thread(target=client_two.port_listen, daemon=True)
c2_listener.start()

while True:
    message = input()
    for user in [client_one, client_two]:
        user.message_client(message)

Client

import socket
from threading import *
import time

SERVER = input("Server IP address: ")
CLIENT_NAME = socket.gethostname()
CLIENT = socket.gethostbyname(CLIENT_NAME)

s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect((SERVER , 4141))


def listener():
    while True:
        message = s.recv(4096)
        print(f"[IN] Server: {s.recv(4096).decode('utf-8')}")
        message = "";
        


# server confirmation message
print(s.recv(4096).decode("utf-8"))


listener_daemon = Thread(target=listener, daemon=True)
listener_daemon.start()

try:
    while True:
        message = input("You: ")
        s.send(message.encode("utf-8"))

        if message == "/BYE":
            s.shutdown(socket.SHUT_RDWR)
            s.close()
            print(f"[-] Connection with {SERVER} closed by user")
            break
except:
        print("Error")

Like I said, I've tried debugging it. I assume it's caught in a while loop, but I've had trouble finding the loop and fixing the problem. Thanks in advance :)

0

There are 0 best solutions below