简易问答机器人服务器
import socket
import threading
dicta ={'你好':'你好','我爱你':'我也爱你','郭睿':'I LOVE YOU'}
class RobotServer():
def __init__(self, ip = '10.0.14.138' ,poin = 8080, connecSize = 100):
'''
:param ip: 服务器IP
:param poin: 服务器端口
:param connecSize: 服务器默认的并发数量
'''
self.__ip = ip
self.__poin = poin
self.__connecSize = connecSize
pass
def startServer(self):
'''
RobotServer类中的方法,用于启动服务器
:return:
'''
ser = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ser.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
ser.bind((self.__ip,self.__poin))
ser.listen(self.__connecSize)
while True:
clientConn, clientAddress = ser.accept()
A = workThread(clientConn)
A.start()
pass
'''
功能:服务器主要功能,接受客户端的信息,处理后将信息发送回客户端。
该类为线程类,目的是实现多客户端可以同时访问该服务器
'''
class workThread(threading.Thread):
def __init__(self,Conn,bufferSize=8096):
'''
:param Conn: 连接的客户端的套接字
:param bufferSize: 接受信息大小
'''
threading.Thread.__init__(self)
self.__Con = Conn
self.__bufferSize = bufferSize
pass
def run(self):
result = ''
receiveMsg = self.__Con.recv(self.__bufferSize)
receiveMsg = receiveMsg.decode('utf-8')
lista = []
for temp in dicta.keys():
lista.append(temp.count(receiveMsg))
if max(lista) == 0:
result = '你说啥!'
else:
index = lista.index(max(lista))
result = dicta[list(dicta.keys())[index]]
self.__Con.send(result.encode('utf-8'))
self.__Con.close()
if __name__ == '__main__':
A = RobotServer()
A.startServer()