在python3 startswith似乎总是返回True

时间:2016-04-23 21:26:04

标签: python sockets startswith

我正在使用一个简单的套接字程序,需要测试客户端发送给服务器的值。我正处于可以在服务器上打印客户端输入的位置,但是当我使用“startswith”测试时,发送的任何数据都返回True

代码:

'''
    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()

2 个答案:

答案 0 :(得分:3)

每次收到数据时,都会使用以下行将其附加到变量commandz:

commandz += data.decode()

似乎你永远不会重新初始化commmandz。因此,它始终以您第一次收到的第一个数据开始。

我认为代码中的print(commandz)行会输出如下内容:

FirstData
FirstDataSecondData
FirstDataSecondDataThirdDataAndEtcEtc

您可能会注意到所有这些字符串都以“F”开头。

答案 1 :(得分:0)

您需要重新初始化commandz,否则您将始终获得以F开头的输出,因为它只是将新数据附加到第一个数据并打印

相关问题