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

  • Context: Python 
  • Thread starter Thread starter ShaddollDa9u
  • Start date Start date
  • Tags Tags
    Code Python Socket
Click For Summary

Discussion Overview

The discussion revolves around troubleshooting a Python socket server that is not responding as expected when receiving data. Participants explore issues related to data encoding, string comparison, and the handling of newline characters. The scope includes technical explanations and debugging strategies.

Discussion Character

  • Technical explanation
  • Exploratory
  • Debate/contested

Main Points Raised

  • One participant shares their initial socket server code and describes the issue of always receiving "nope" instead of "works" when sending "blabla".
  • Another participant suggests using print statements to debug what data the server is receiving, recommending to check for whitespace characters.
  • A participant reports that the server is receiving data as bytes, specifically noting the presence of a newline character in the received string.
  • There is a discussion about the need to convert bytes to strings and the appropriate use of the strip() method to handle trailing newlines.
  • One participant mentions using the Linux command "telnet" to connect to the server, indicating a lack of a dedicated client code.
  • Another participant points out that the comparison in the if condition may be failing due to leading/trailing characters in the received data.
  • Participants discuss the importance of understanding the exact output of print statements to diagnose the issue effectively.
  • One participant successfully resolves the issue by modifying the if condition to check for substring presence instead of equality, while another suggests using the strip() method to clean the data.

Areas of Agreement / Disagreement

Participants generally agree on the importance of handling data encoding and whitespace correctly, but there are multiple approaches discussed regarding how to achieve the desired functionality. The discussion remains somewhat unresolved as participants explore different debugging strategies and code modifications.

Contextual Notes

Limitations include the absence of the client code, which may be critical for fully understanding the issue. Participants also note the potential for trailing newline characters affecting string comparisons.

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 ·
Replies
1
Views
2K