我正在工作和一个简单的套接字程序,并需要测试客户端发送到服务器的值。我在一个地步,我可以打印服务器上的客户端输入,但任何数据发送,则返回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()
不要使用'进口*'第一个数据并打印。另外,你确定你想要低层'_thread'而不是其中一个高层模块吗? – ThiefMaster
'127'不是非特权端口。你需要一个大于1024的。 – ThiefMaster
你能详细说明导入*有什么问题吗?对此语言不熟悉,欢迎所有反馈。 – WillMc