robot.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import demjson
API_KEY = '5e0b241b7507443ca4a9eac826d0620f'
def send_msg(msg, userID):
url = "http://openapi.tuling123.com/openapi/api/v2" # 接口地址
json_params = {
"reqType": 0,
"perception": {
"inputText": {
"text": msg
},
},
"userInfo": {
"apiKey": API_KEY,
"userId": userID
}
}
response = requests.post(url, json=json_params)
json_obj = demjson.decode(response.text)
print(json_obj)
return json_obj['results'][0]['values']['text']
# if __name__ == '__main__':
# send_msg('hello world', '123456789')
# 参考图灵机器人 Web API
server.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from tcpdemo.robot import send_msg
import redis
import socket
import time
cache = redis.Redis() # 用redis缓存
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) # 创建socket对象, SOCK_STREAM tcp, SOCK_DGRAM udp
sock.bind(('127.0.0.1', 8001)) # 绑定本地ip和端口
sock.listen() # 监听
client_sock, (client_ip, client_port) = sock.accept() # 接收客户端发来的请求, 如果没有则会一直阻塞直到有为止(参数:socket对象, 地址, 我将client_address拆分为ip和port)
# 判断userID是否在缓存中, userID需要是个额整数
if cache.exists(client_ip):
userID = int(cache.get(client_ip))
else:
userID = str(int(time.time()))
cache.set(client_ip, userID) # 保存userID
# 循环读写操作
while True:
try:
client_msg = client_sock.recv(1024) # 保存客户端传过来的数据
client_sock.send(send_msg(client_msg.decode(), userID).encode())
print('接收到的客户端的消息: ', client_msg.decode())
except ConnectionResetError as e:
print('客户端下线了')
break
client_sock.close() # 关闭
client.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
sock = socket.socket() # 创建socket对象
sock.connect(('127.0.0.1', 8001)) # 连接ip
while True:
msg = input('请输入内容: ')
sock.send(msg.encode())
server_msg = sock.recv(1024) # 把服务端传过来的数据保存
print('接收到的服务端的消息: ', server_msg.decode()) # 解码服务端传过来的数据
sock.close() # 关闭