Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python Socket problem in python

  1. Aug 12, 2017 #1
    Hi everyone, I have just started learning sockets in python and I have made the following code:

    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.
     
  2. jcsd
  3. Aug 12, 2017 #2

    Ibix

    User Avatar
    Science Advisor

    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.
     
  4. Aug 12, 2017 #3
    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 ??
     
  5. Aug 12, 2017 #4

    Ibix

    User Avatar
    Science Advisor

    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.
    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.
     
  6. Aug 12, 2017 #5
    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
     
  7. Aug 12, 2017 #6

    Ibix

    User Avatar
    Science Advisor

    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.
     
  8. Aug 12, 2017 #7
    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?
     
  9. Aug 12, 2017 #8

    Ibix

    User Avatar
    Science Advisor

    Post your revised code.
     
  10. Aug 12, 2017 #9
    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 :

    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)
                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()
     
  11. Aug 12, 2017 #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) "?
     
  12. Aug 12, 2017 #11

    Ibix

    User Avatar
    Science Advisor

    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.
     
  13. Aug 12, 2017 #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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Socket problem in python
  1. Python problem (Replies: 3)

  2. N-body problem in Python (Replies: 10)

Loading...