思路:首先,客户端和服务端建立socket连接,然后客户端向服务端发送消息,服务端接收消息,并调用 图灵机器人API接口,获取回复返回给客户端。
server端: import socket import time import threading import requests import json class ChatServer: def __init__(self, port): # 绑定服务器的ip和端口,注意以tuple的形式 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(("0.0.0.0", port)) self.socket.listen(5) # 图灵机器人,授权码 self.key = "6fd2ff147c794ecfb2fbb40ecb3df4d3" print("正在监听 127.0.0.1 :{}...".format(port)) def tcplink(self, sock, addr): # 每次连接,开始聊天前,先欢迎下。 sock.send("你好,欢迎来到机器人聊天器!".encode("utf-8")) while True: data = sock.recv(1024).decode("utf-8") print(sock.getpeername()) print(sock.getsockname()) print(sock.fileno()) username = data.split("::")[0] msg = data.split("::")[1] if msg == "exit": break if msg: print("【"+username+"】 "+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time()))) print(msg) response = self.get_response(msg) sock.send(response.encode("utf-8")) sock.close() print("与 {} 结束聊天!".format(username)) def get_response(self, info): # 调用图灵机器人API url = 'http://www.tuling123.com/openapi/api?key=' + self.key + '&info=' + info res = requests.get(url) res.encoding = 'utf-8' jd = json.loads(res.text) return jd['text'] def main(self): while True: sock, addr = self.socket.accept() t=threading.Thread(target=self.tcplink, args=(sock, addr)) t.start() if __name__ == '__main__': cs = ChatServer(port=9999) cs.main()
client端: import socket import time class ChatClient: def __init__(self, username, port): self.username = username self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(("127.0.0.1", port)) def send_msg(self, msg): self.socket.send("{username}::{msg}".format(username=self.username,msg=msg).encode("utf-8")) def recv_msg(self): data=self.socket.recv(1024) if data: print(" 【机器人小图】"+" "+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time()))) print(data.decode("utf-8")) return True return False def main(self): data = self.socket.recv(1024) print(data.decode("utf-8")) msg = input("请输入消息:") self.send_msg(msg) while True: if self.recv_msg(): msg=input(" 我:") self.send_msg(msg) if msg == "exit": print("聊天室已关闭") break if __name__ == '__main__': cc = ChatClient(username="小明", port=9999) cc.main()