Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

Python: message not sending in sockets

I'm working in a sockets Python project, I encountered a bug in where I was not able to send two or more different messages from server to client. Here, for example, if the client requests to log in, the server answers with [CODE 10] Log in request and immediatly I wanted to respond if the log in was successful or not:

conn.send("[CODE 10] Log in request".encode(FORMAT))
                success_login = login(current_username, current_password)
                if success_login:
                    conn.send("[CODE 110] Log in successful".encode(FORMAT))
                else:
                    conn.send("[CODE 111] Log in error".encode(FORMAT))

Instead I must press enter in client prompt between [CODE 10] Log in request and one of CODE 110 or CODE 111 response, is the anything wrong with my implementation?

I think it has to deal with client.py in the infinite loop but not sure how to fix it, can anyone tell me what I am doing wrong?

client.py

import socket

HEADER = 64
PORT = 9999
FORMAT = 'utf-8'
DISSCONECT_MESSAGE = b'0'
SERVER = 'localhost'
ADDRESS = (SERVER,PORT)

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

client.connect(('localhost', 9999))

def send(msg):
    message = msg.encode(FORMAT)
    msg_length = len(message)
    send_length = str(msg_length).encode(FORMAT)
    send_length += b' ' * (HEADER - len(send_length))
    client.send(send_length)
    client.send(message)
    print(client.recv(1024).decode(FORMAT))

while True:
    msg = input()
    if msg.encode() == DISSCONECT_MESSAGE:
        print("[DISSCONECTED FROM SERVER]")
        client.send(DISSCONECT_MESSAGE)
        break
    else:
        send(msg)

server.py

import socket
import threading

from dbms import *


HEADER = 64
PORT = 9999
SERVER = socket.gethostbyname(socket.gethostname())
ADDRESS = ('',PORT)
FORMAT = 'utf-8'
DISSCONECT_MESSAGE = b'0'

exec(open('dbms.py').read())

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDRESS)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected")

    connected = True

    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length == '0': # DISSCONECT_MESSAGE decoded
            connected = False
            break
        elif msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)

            # sign in
            if msg[:2] == "50":
                new_usuario = msg.split()[1]
                new_password = msg.split()[2]
                conn.send("[CODE 50] Request to sign in".encode(FORMAT))
                success_insert = insert(new_usuario , new_password) 
                if success_insert: 
                    conn.send("[CODE 510] Sign in successful".encode(FORMAT))
                else:
                    conn.send("[CODE 511] Sign in error".encode(FORMAT))

            # log in
            if msg[:2] == "10":
                current_username = msg.split()[1]
                current_password = msg.split()[2]
                conn.send("[CODE 10] Solicitud para inicio de sesion".encode(FORMAT))
                success_login = login(current_username, current_password)
                if success_login:
                    conn.send("[CODE 110] Log in successful".encode(FORMAT))
                else:
                    conn.send("[CODE 111] Log in error".encode(FORMAT))


            print(f"[{addr}] {msg}")
            conn.send("Message recived".encode(FORMAT))

    print(f"[{addr}] DISSCONNECTED")
    conn.close()
    exit()



def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept() # Wait to a new connection
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount()-1}")


print("[STARTING] Server is starting...")
start()
exit()

dbms.py

import psycopg2

print("[IMPORT] dbms.py imported correctly")

conn_db = psycopg2.connect(database="aaa", user = "bbb", password = "ccc", host = "127.0.0.1", port = "5432")

print("[DATABASE] Successfully connected with database")

cursor = conn_db.cursor()

def insert(new_usuario,new_password):

    try:

        postgres_insert_query = """ INSERT INTO users (username, password) VALUES (%s,%s) """
        record_to_insert = (new_usuario, new_password)
        cursor.execute(postgres_insert_query, record_to_insert)

        conn_db.commit()
        count = cursor.rowcount

        print(count, "[DATABASE] Record inserted successfully into USERS table")
        return True
    except (Exception, psycopg2.Error):
        if(conn_db):
            print("[ERROR] Failed to insert record into table USERS")
            return False


def login(current_username, current_password):
    """ Validate if a user already exists in DB """

    try:
        postgres_query = """SELECT username, password FROM users WHERE username = %s AND password = %s"""
        record_to_validate = (current_username, current_password)
        cursor.execute(postgres_query, record_to_validate)

        count = cursor.rowcount

        print(count, "[DATABASE] Credentials validated successfully")
        return True

    except (Exception, psycopg2.Error):
        if(conn_db):
            print("[ERROR] Failed to validate credentials")
            return False
question from:https://stackoverflow.com/questions/65877998/python-message-not-sending-in-sockets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...