python rpyc的应用 ——聊天的功能(带认证)

♀尐吖头ヾ 提交于 2019-12-02 22:15:17

rpc:远程过程调用,一个协议,实现的语言有很多。顾名思义,在A机器远程调用B机器里面的函数。 rpyc:python的远程过程调用。

首先是安装,我的环境:centos6.5

cd /usr/local/src/
 wget https://pypi.python.org/packages/source/r/rpyc/rpyc-3.2.3.tar.gz --no-check-certificate  
tar -zxvf rpyc-3.2.3.tar.gz 
cd rpyc-3.2.3
python setup.py install

测试下,运行

[root@Master rpyc-3.2.3]# python -c 'import rpyc'

没有错误就说明安装好了

现在做一个功能就是聊天会话的功能,理解下。 一个server端,一个client端。

vim server.py 输入:

[root@Master rpyc-3.2.3]# vim server.py 
#-*- encoding: utf-8 -*-
from rpyc import Service
from rpyc.utils.server import ThreadedServer

class ManagerService(Service):
    #rpyc只传送exposed_开头的函数
    #进行连接用户认证 user和passwd 随便起一个,和linux用户没关系
    def exposed_login(self,user,passwd):
        if user=="root" and passwd=="KJS23o4ij09gHF734iuhsdfhkGYSihoiwhj38u4h":
            self.Checkout_pass=True
        else:
            self.Checkout_pass=False
    #认证成功后执行接收到的命令关返回结果
    def exposed_cmd(self,command):
        try:
            if self.Checkout_pass!=True:
                return "User verify failed!"
        except:
            return "Invalid Login!"


        print "他说:",command
        ret=raw_input("我说:")
        return ret

#启动进程服务
s=ThreadedServer(ManagerService,port=11511,auto_register=False)
s.start()

这个地方注意下:待会先启动server.py

然后再开启一个终端(或者是装了rpyc的其他机器,连接的时候将127.0.0.1换成server的ip) vim client.py

#-*- encoding: utf-8 -*-
import rpyc
conn=rpyc.connect('127.0.0.1',11511)
conn.root.login('root','KJS23o4ij09gHF734iuhsdfhkGYSihoiwhj38u4h')
while 1:
        command=raw_input("我说:")
        message=conn.root.cmd(command)
        print "他说:",message

写好了过后,注意!!!!!!!!! 先启动server.py 然后启动client.py

输入图片说明

rpyc用来聊天? 也太低级了。 换位思考下,都能交互了,还有啥不能做。 client发送命令,server获取了,然后去执行,还有什么不能做的。 参考: rpyc 官网:http://rpyc.readthedocs.org/en/latest/index.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!