0

现在,我正在尝试在 Python 中创建一个套接字服务器,它接收来自客户端的输入,处理它,做任何需要做的事情,然后向客户端发送一条消息,表明它已经完成。

我现在遇到的问题是系统无法识别客户端发送的命令。我目前正在使用if语句来比较字符串。接收到的数据被解码为 UTF-8。我不明白为什么if声明不能比较它们。

'''
    Simple socket server using threads
'''

import socket
import sys
from thread import *
import cmd

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 8888 # 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\n') #send only takes string

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

        #Receiving from client
        databyte = conn.recv(1024)
        reply = 'OK...' + data
        data = databyte.decode('utf-8')
        if data == 'light'
            print 'light'
        if not data: 
            break

        conn.sendall(reply)

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

任何帮助,将不胜感激!先感谢您!

4

0 回答 0