2016-04-23 95 views
0

我正在工作和一個簡單的套接字程序,並需要測試客戶端發送到服務器的值。我在一個地步,我可以打印服務器上的客戶端輸入,但任何數據發送,則返回true,當我用「startswith」測試在python3 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() 
+0

不要使用'進口*'第一個數據並打印。另外,你確定你想要低層'_thread'而不是其中一個高層模塊嗎? – ThiefMaster

+0

'127'不是非特權端口。你需要一個大於1024的。 – ThiefMaster

+0

你能詳細說明導入*有什麼問題嗎?對此語言不熟悉,歡迎所有反饋。 – WillMc

回答

3

每次接收數據的時間,你可以用下面的命令將它追加到變量commandz中:

commandz += data.decode() 

看起來你從來沒有重新初始化commmandz。所以,它總是從您第一次收到的第一批數據開始。

我假設print(commandz)行代碼中的輸出,你是這樣的:

FirstData 
FirstDataSecondData 
FirstDataSecondDataThirdDataAndEtcEtc 

您可能會注意到,所有這些字符串以「F」開頭。

+0

這樣做了。我是python的新手,所以我錯過了+ =正在拼接。感謝您的快速回復。 – WillMc

0

您需要重新初始化commandz否則你總是會得到一個輸出以F起它只是新數據追加到