本人是从事php开发的, 近来想通过php实现即时通讯(兼容windows)。后来发现实现起来特别麻烦, 就想到python。听说这家伙在什么地方都能发挥作用。所以想用python来做通讯模块。。。所以主要学习pythonn的多线程和tcp连接。
但是没有用过python, 所有在学习python的同时写个小小的程序 -》 和机器人聊天
本程序机器人由【图灵机器人 http://www.tuling123.com】提供, 把编写的例子发了出来供初学python的朋友们学习和熟悉。
注意:python版本必须为3.x +, 不兼容2.x版本的python
文件列表:
main_server.py: 服务端程序,用于接收客户端的信息, 并返回Jinko回答的话
# tcp server
import socket;
import time;
import threading;
from JinkoRobot import *; #应用程序入口类
class ApplicationServer: #构造函数初始化 socket
def __init__(self, host="localhost", port=8005):
self.connList = [];
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
self.socket.bind((host, port));
self.socket.listen(100);
print("我是Jinko, 我来自[图灵机器人:http://www.tuling123.com]");
print("");
print("赶紧打开客户端和我聊天吧!");
self.accept(); #多线程接受用户请求
def accept(self):
while True:
connection, address = self.socket.accept();
# print('connect')
thread = ChatThread(connection);
thread.start(); #聊天线程
class ChatThread(threading.Thread): def __init__(self, conn):
threading.Thread.__init__(self);
self.__connection = conn; def run(self):
while True:
try:
recv = self.__connection.recv(8192);
except:
break; # print("收到:" + recv.decode('utf-8'))
rebot = JinkoRobot();
rebot.listenFor(recv.decode('utf-8'));
answer = rebot.answer();
# print('say:' + answer)
self.__connection.send(answer.encode('utf-8')); ApplicationServer();
main_client.py: 客户端程序, 用于和Jinko发起聊天
import socket;
import time; sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
print("正在和Jinko连线...");
sock.connect(('localhost', 8005));
print(""); while True:
speak = input("和Jinko说点什么:"); if speak == "quit":
break; if speak == "":
continue; # print("发送中..." + "("+ speak +")")
sock.send(speak.encode('utf-8'));
# print("已发送") print("Jinko在思考...");
answer = sock.recv(8192);
print("Jinko回复你:" + answer.decode('utf-8'));
print(""); sock.close();
JinkoRobot.py: 它就是Jinko啦啦啦~~
#Jinko Robot
import json;
import urllib.request;
import urllib.parse; class JinkoRobot: __answer = ''; def __init__(self):
pass; #倾听话语
def listenFor(self, string):
self.__answer = self.thinking(string); # 思考着
def thinking(self, string):
says = urllib.parse.quote_plus(string);
f = urllib.request.urlopen("http://www.tuling123.com/openapi/api?key=4bc32d41c10be18627438ae45eb839ac&info=" + says);
json_str = f.read();
thinkdata = json.loads(json_str.decode('utf-8'));
f.close(); if(thinkdata['code'] > 40000 and thinkdata['code'] < 40010):
return "今天Jinko被你问得有点累了, 过会再问吧!"; if(thinkdata['code'] == 200000):
return thinkdata['text'] + ", 猛戳这里>>" + thinkdata['url']; if(thinkdata['code'] == 302000) :
info = thinkdata['text']; for content in thinkdata['list']:
info += "\n\n>" + content['article'] \
+ " 来源于" + content['source'] \
+ " 详细信息请猛戳这里>>" + content['detailurl']; return info; if(thinkdata['code'] == 305000):
info = thinkdata['text']; for key in thinkdata['list']:
info += "\n\n>" + key + ": 车次>" + content['trainnum'] \
+ " 从" + content['start'] + "到" + content['terminal'] \
+ " 发车时间:" + content['starttime'] \
+ " 到达时间:" + content['endtime'] \
+ " 详细信息请猛戳这里>>" + content['detailurl']; return info; return thinkdata['text']; #和你交流回答
def answer(self):
return self.__answer;
运行效果图:
最后我想说下, 我只是python的初学者,没啥python经验哈
顺便提供下zip下载包:http://files.cnblogs.com/files/JinkoWu/ChatWithRobot.zip