Search code examples
pythonsocketsstartswith

In python3 startswith always seems to return True


I am working and a simple socket program and need to test the value sent by the client to the server. I'm at a point where I can print the the clients input on the server, but any data sent returns True when I test it with "startswith"

Code:

'''
    Simple socket server using threads
'''

import socket
import sys
from _thread import *

HOST = ''
PORT = 127 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created")

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print("Bind failed. Error Code : " + str(msg[0]) + " Message " + msg[1])
    sys.exit()

print("Socket bind complete")

#Start listening on socket
s.listen(10)
print("Socket now listening")

#Function for handling connections. This will be used to create threads
def clientthread(conn):

    #Sending message to connected client
    #conn.send("Welcome to the server. Type something and hit enter") #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    commandz = ""
    while True:


        #Receiving from client
        data = conn.recv(1024)
        commandz += data.decode()
        #reply = "OK..." + commandz
        print(commandz)
        if commandz.startswith( 'F' ):       
            print("Forwardmove")
        else:
            print("Not forward") 
        if not data: 
            break

        #conn.sendall("heard you")

    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print("Connected with " + addr[0] + ":" + str(addr[1]))

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()

Solution

  • Each time you receive data, you append it to the variable commandz, using this line :

    commandz += data.decode()
    

    It seems that you never reinitialize commmandz. So, it always starts with the first data you received the very first time.

    I suppose that the print(commandz) line in your code outputs you something like this :

    FirstData
    FirstDataSecondData
    FirstDataSecondDataThirdDataAndEtcEtc
    

    You may notice that all these strings starts with "F".