Python:消息未在套接字中发送

时间:2021-01-25 01:54:56

标签: python sockets

我在一个套接字 Python 项目中工作,我遇到了一个错误,我无法从服务器向客户端发送两个或更多不同的消息。在这里,例如,如果客户端请求登录,服务器会回复 [CODE 10] Log in request 并且我想立即响应登录是否成功:

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

相反,我必须在 [CODE 10] Log in requestCODE 110CODE 111 响应之一之间的客户端提示中按 Enter,我的实现有什么问题吗?

我认为它必须在无限循环中处理 client.py 但不知道如何解决它,谁能告诉我我做错了什么?

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

0 个答案:

没有答案
相关问题