Python Why am I getting 'nope' instead of 'works' when using sockets in Python?

AI Thread Summary
The discussion revolves around troubleshooting a Python socket server code that fails to respond correctly to a specific input. The initial issue was that the server always returned "nope" instead of "works" when the string "blabla" was sent. The problem was identified as stemming from the way data was received, which included trailing newline characters, making direct string comparison ineffective. Participants suggested using debugging techniques, such as printing the received data with added markers to identify whitespace characters. It was noted that the data received was in bytes, requiring conversion to a string format. The solution involved using the `strip()` method to remove unwanted characters from the input. Ultimately, the user resolved the issue by modifying the condition to check for the presence of "blabla" within the received data instead of checking for an exact match, leading to successful responses from the server.
ShaddollDa9u
Messages
18
Reaction score
0
Hi everyone, I have just started learning sockets in python and I have made the following code:

Python:
import socket

HOST = ''                
PORT = 8888            
def main():
   
    while 1:
       
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(1)
        conn, addr = s.accept()
       
       
        while 1:
           
            data = conn.recv(1024)
           
           
           
            if ( data == "blabla"):
                conn.send("works")
            else:
                conn.send("nope")

       
        conn.close()
        s.close()
if __name__ == '__main__':
    main()

so obviously, when I connect to that server and send "blabla", I should normally get "works" as an answer, but somehow, I always get the "nope" like if the if condition was not respected. Can you please help me to solve this ??

PS : I use python 3.6 in Linux.
 
Technology news on Phys.org
What does the server think it's getting? A debugger is the Right Way to do that, but adding a print instruction would probably be a start.

Hint: Don't just print the string, add a "##" at the beginning and end so you see any whitespace characters.
 
I have tried to put print(data) before the if condition. It seems that the server is getting ---> b'quit\r\n'
How do I fix it ??
PS: if I add ##, the following code wouldn't be considered as a comment ??
 
ShaddollDa9u said:
I have tried to put print(data) before the if condition. It seems that the server is getting ---> b'quit\r\n'
I'd guess your client program isn't doing what you think it's doing. Interesting that the first character in the output is a b - what if you type something else? Is it just sending the first character? You haven't posted your client code, though, so that's only a guess.
ShaddollDa9u said:
PS: if I add ##, the following code wouldn't be considered as a comment ??
I meant print("#"+data+"#"). Doesn't have to be # characters if you want to use something else. It doesn't matter anyway, as you've obviously got something other than a trailing newline problem.
 
All the data seems to be received as " b'*my data*\r\n' ". I didn't make a client code, I connect to the server by the Linux command "telnet localhost 8888".

The weirdest thing is that when I put print("#"+data+"#") as you said, I have the following error :

Traceback (most recent call last):
File "ip.py", line 37, in <module>
main()
File "ip.py", line 22, in main
print("#"+data+"#")
TypeError: must be str, not bytes

This is getting really weird lol
 
I missed the apostrophes in there. The initial b is telling you that what follows between the apostrophes is raw bytes, not a string.

Convert it to a string using str() and strip the newline with the strip() method.
 
I have converted now in str() but still getting " b'*my data*\r\n' ". What arguments do I have to put in strip to keep only my data?
 
Post your revised code.
 
Now I have tried to put data = data.decode() and it seems that I don't have the " b'*my data*\r\n' " thing anymore, but still, the if condition is note satisfied. Here is my code now :

Python:
import socket

HOST = ''                
PORT = 8888        
def main():
   
    while 1:
       
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(1)
        conn, addr = s.accept()
       
       
        while 1:
           
            data = conn.recv(1024)
            data = str(data.decode())
           
            print(data)
           
           
            if(data == "blabla"):
                conn.send("works")
            else:
                conn.send("nope".encode()) #It seems that bytes are required for conn.send, not str

       
        conn.close()
        s.close()
if __name__ == '__main__':
    main()
 
  • #10
I think you need to post the client code. We are only seeing half of what we need.

I've written socket code in python, but I'd have to look to refresh myself on the details. One thing though, I see you are coding " if ( data == "blabla"): ", that may be your problem. What is coming back looks to have leading/trailing chars, in addition to your data (" b'*my data*\r\n'"). So change your code to see if your string contains "blabla", instead of is equal to "blabla". Or if the placement of your string is predictable (I think it will be), look only at that sub-string for a match.

edit - just saw your recent post - instead of telling us "condition not satisfied", you need to tell us what was found. That's the key to why it wasn't satisfied. You (and we) are in the dark w/o that info.

What was the output of " print(data) "?
 
  • #11
Right. Because the data you're sending includes trailing newlines, so "blabla\r\n" doesn't match "blabla". The strip() method of str removes trailing newlines without any arguments (at least it does in python 2) add a strip() and you should be good.
 
  • #12
Yeah it works ! Thanks guys !
I didn't use the strip() method, I have just replaced the if condition by if("blabla" in data) and now it works fine.
Thanks for the help guys.
 

Similar threads

Replies
1
Views
2K
Back
Top