简体   繁体   中英

Python chat client: the server receives commands along with previously sent messages

I'm currently working on a project for a class. It consists in code a simple chat client (protocol given by the teacher) to do (at first) some simple tasks.

My problem is that after I send a mensage on the globlal channel or in other channel that doesn't require the use of a command, and try to send any command, the server replies with an error, saying something like: "msgbeforemsgbeforeCOMMAND" is not a valid command. I just cannot figure it out why this is happening...

( another thing, note that my dictionary is not printing the right why, I dont know why to )

ex: chat running

import socket, select, string, sys
import threading
import time

def prompt():
    sys.stdout.write('<You>: ')
    sys.stdout.flush()

tLock = threading.Lock()
shutdown = False

def receber(sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data = sock.recv(1024)
                if not data:
                    print ('Disconnected from server\n')
                    sys.exit()
                else:
                    print ('<server>: %s' % (data.decode()))
                    sys.stdout.write(data)
        except:
            pass
        finally:
            tLock.release()


#Main Function
if __name__ == "__main__":

    host = 'mini.alunos.di.uevora.pt'
    port = 143

    #IP do servidor
    try:
        busca_ip = socket.gethostbyname( host )
        print ('Chat server IP: %s Port: %d \nNow connecting...\n' %(busca_ip, port))

    except socket.gaierror:
        #Não conseguiu o IP do servidor
        print ('Hostname could not be resolved. Exiting.')
        sys.exit()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(3)

    # connectar ao host
    try :
        s.connect((busca_ip, port))
        s.setblocking(0)
    except :
        print ('Unable to connect to the server.')
        sys.exit()

    print ('Connected to chat server. You may start chatting\n')

    COM_ARG = {'_Comando_': '_Argumentos_',
               'NICK': '<nickname> [\<password>]',
               'MSG': '<recipient> \<message>',
               'ENTER': '<room>',
               'LEAVE': '<room> [\<message>]',
               'RLIST':'',
               'ULIST':''}

    for chave, valor, in COM_ARG.items():
        print (("%s %s") % (chave,valor))

    print ('\n')

    comandos = COM_ARG.keys()


    #criar thread para o socket
    t = threading.Thread(target = receber, args=(s,))
    t.start()

    while True:

        msg = input('<You>: ')
        msg = msg.strip()
        msg12 = msg.upper()
        msg12 = msg12.split()
        try:
            if msg12[0] in comandos:
                msg = msg + '\n'
        except:
            pass
        s.send(msg.encode())
        time.sleep(0.25)

btw, sys.stdout.write(data) is doing something there?

Hope you could help me out.

(another thing, note that my dictionary is not printing the right why, I dont know why to)

Dictionary doesn't respect order.

My problem is that after I send a mensage on the globlal channel or in other channel that doesn't require the use of a command, and try to send any command, the server replies with an error, saying something like: "msgbeforemsgbeforeCOMMAND" is not a valid command. I just cannot figure it out why this is happening...

It's not just a problem with the code, the server recives the msgs, and keeps them until a '\\n' appears, just then interprets the command. It's a "problem" with the protocol, but the code must be changed.

btw, sys.stdout.write(data) is doing something there?

Supposedly does the samething that print (data.decode()) does, but doesn't work in my case. I'm not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM