OPato
OPato

Reputation: 13

TCP server not receiving data correctly in Python

I'm trying to make a TCP server in Python in which you have to login to be able enter, but when verifying if the user can enter, it always says the user cannot be found, even when the user is supposed to be able to enter. This is the server code:

import socket
from threading import *


class user:
    def __init__(self, username, password):
        self.username = username
        self.password = password


user1 = user('user', 'pass')

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 9000
serversocket.bind((host, port))


class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            self.sock.send(b'LOGIN\n')
            self.sock.send(b'Username:')
            name = self.sock.recv(1024).decode()
            print(name)
            print(user1.username)
            self.sock.send(b'Password:')
            pw = self.sock.recv(1024).decode()
            print(pw)
            print(user1.password)
            if (name == user1.username) and (pw == user1.password):
                self.sock.send(b'Welcome, ', name)
            else:
                self.sock.send(b'User not found.')


serversocket.listen(5)
print('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

I'm using telnet to communicate with the server and I can see that the input is correct. This is the output which confirms that they're similar:

server started and listening
user

user
pass

pass

This is the telnet console:

LOGIN
Username:user
Password:pass
User not found.

Any help is appreciated. Thanks

Upvotes: 1

Views: 102

Answers (1)

Torxed
Torxed

Reputation: 23480

The expected input from telnet to the server isn't what you think it is.
Since telnet adds a trailing \n at the end of the transmitted string, you need to strip the incoming data. So the simplest approach would be:

name = self.sock.recv(1024).decode().strip()
pw = self.sock.recv(1024).decode().strip()

Strip simply removes trailing white spaces and is probably most suitable here.
You can debug and check if this is the case by doing:

print([name])

As a dirty workaround to see the actual contents of the string and not just the printed representation in the terminal. it should show you user\n instead of user which you expect. And it's always a good idea to print or debug your variables to verify the content is what you expect it to be.

Upvotes: 1

Related Questions