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

In summary: data = conn.recv(1024) if ( data == "blabla"): conn.send("works") else: conn.send("nope") conn.close()
  • #1
ShaddollDa9u
18
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
  • #2
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.
 
  • #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 ??
 
  • #4
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.
 
  • #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
 
  • #6
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.
 
  • #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
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.
 

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

1. What is a socket in python?

A socket in python is a communication endpoint that allows for bidirectional data transfer between a client and server. It acts as a door for information to pass through, allowing for network communication between different devices or processes.

2. How do I create a socket in python?

To create a socket in python, you can use the built-in socket module. First, you need to import the module and then use the socket() function to create a socket object. You can specify the type of socket you want to create (e.g. TCP or UDP) and the address family (e.g. IPv4 or IPv6).

3. What is a socket timeout in python?

A socket timeout in python refers to the amount of time a socket will wait for a response from the other end before throwing an error. It is important to set a timeout to prevent a program from getting stuck if the other end is not responding.

4. How do I handle errors with sockets in python?

To handle errors with sockets in python, you can use try and except statements. This allows you to catch and handle specific errors that may occur during socket communication. It is also important to properly close sockets after use to prevent errors and ensure efficient use of system resources.

5. Can I use sockets in python for web development?

Yes, you can use sockets in python for web development. The socket module can be used to create a server-side socket that can handle incoming client requests. This can be useful for building web applications that require real-time communication, such as chat applications or multiplayer games.

Similar threads

  • Programming and Computer Science
Replies
1
Views
1K
Back
Top