Question and Answer Applet for Smart Robots (Connection of socket and threading)

Keywords: encoding socket Python

Intelligent question and answer robot

Problem Description

	Define a set of questions and answers to be stored in a list on the server side. More than 10 questions are keys, value is the standard answer, for example: [{Hello:'Hello'}, {I love you':'I love you too'}...], when the client enters a statement, the server side will appear k most frequently in all keys according to each word in the statementEy's value is the answer, returns to the customer, and implements intelligent question and answer.

Methodological thinking

1. Set a fixed ip, port number, concurrent number on the server side (i.e., access by up to a few clients together)
2. Server-initiated host (multi-threaded concurrent synchronization), waiting for client access, starting separate threads, handling each user request.
3. A separate thread on the server returns an answer based on the question entered by the client.
4. Clients connect to the server's ip and port, enter questions, wait for answers

Code Samples

Server Side

class RobortServer():
    def __init__(self,ip = '10.0.14.45',port = 8090,connectSize = 100):
        '''

        :param port: Server port number
        :param connectSize: Server default number of concurrencies
        '''
        self.__ip = ip
        self.__port = port
        self.__connerctSize = connectSize
        pass
    def startServer(self):
        '''
        //Server Started Host (Multithreaded)
        :return:
        '''
        server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        server.bind((self.__ip,self.__port))
        server.listen(self.__connerctSize)
        while True:
            clientConn,clientAddr = server.accept()   #Waiting for Client Request
            #Start a separate thread to process each user request nio
            wt = WorkThread(clientConn,clientAddr)
            wt.start()
            pass
        pass
    pass

class WorkThread(threading.Thread):
    def __init__(self,connection,addr,bufferSize = 8096):
        threading.Thread.__init__(self)
        self.__connection = connection
        self.__addr = addr
        self.__bufferSize = bufferSize
        pass
    def run(self):
        receiveMsg = self.__connection.recv(self.__bufferSize)
        receiveMsg = receiveMsg.decode('utf-8')
        answer = ""
        for temp in questionlist:
            for i in temp.keys():
                if i.count(receiveMsg) > 0:
                    answer = temp[i]
                    break
        if not answer:
            print("What do you say?")
        self.__connection.send(answer.encode('utf-8'))
        self.__connection.close()
        pass
    pass
if __name__ == "__main__":
    rs = RobortServer()
    rs.startServer()
    pass

Client

from socket import *

class RobotClient():
    def __init__(self,ip = '10.0.14.45',port = 8090,bufferSize = 8096):
        self.__ip = ip
        self.__port = port
        self.__bufferSize = bufferSize
        pass
    def startSendMsg(self,msg):
        client = socket(AF_INET,SOCK_STREAM)
        client.connect((self.__ip,self.__port))
        client.send(msg.encode('utf-8'))
        receive = client.recv(self.__bufferSize)
        print(receive.decode('utf-8'))
        client.close()
        pass

    pass

if __name__ == "__main__":
    rc = RobotClient()
    while True:
        msg = input("You say, I answer:")
        rc.startSendMsg(msg)
    pass

Extension: Differences and usage between encode and decode
Strings are represented as unicode encoding inside Python, so when encoding conversions, unicode is often used as an intermediate encoding, that is, to decode other encode d strings into unicode and then from unicode encoding to another encoding.
Decode is used to convert other encoded strings to unicode encoding, such as str1.decode('gb2312'), which means to convert the GB2312 encoded string STR1 to unicode encoding.
The function of encode is to convert unicode encoding into other encoded strings, such as str2.encode('gb2312'), which means to convert unicode encoded strings STR2 to GB2312 encoding.
To convert other codes to utf-8, you must first decode them into unicode and then re-encode them into utf-8, which uses unicode as the medium of conversion
E.g.'s='Chinese'
The string is utf8 encoding if it is in a utf8 file and gb2312 encoding if it is in a gb2312 file.In this case, to convert the encoding, you need to first convert it to unicode encoding using decode method, and then convert it to other encoding using encode method.Typically, when no specific encoding is specified, code files are created using the system default encoding.
The following:
s.decode('utf-8').encode('utf-8')
decode(): is decoding
encode(): is the code
This article is for reference only. The extended content is Baidu Search. Note that the ip and port number are set to your own

Posted by watson516 on Tue, 13 Aug 2019 18:12:08 -0700