我试图用SSL编程一个最简单的客户机-服务器应用程序,但我对此有一些问题:
1) 如何减少JSON序列化的时间?
2) 也许存在比linereceiver更好的东西,在服务器和客户端之间创建通信?或者我可以增加接收线的长度?在
源代码:
a) 服务器SLL
import server
from twisted.internet.protocol import Factory
from twisted.internet import reactor
from OpenSSL import SSL
class ServerSSL(object):
def getContext(self):
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_certificate_file('server_cert.pem')
ctx.use_privatekey_file('server_key.pem')
return ctx
if __name__ == '__main__':
factory = Factory()
factory.protocol = server.Server
reactor.listenSSL(8000, factory, ServerSSL())
reactor.run()
b)服务器
^{pr2}$c)客户端控制台
from json import dumps, loads
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.internet import ssl, reactor
class ServerClientSSL(LineReceiver):
"""
Basic client for talking with server under SSL
"""
def connectionMade(self):
"""
Send auth request to serverSLL.py
"""
login = raw_input('Login:')
password = raw_input('Password:')
hash_password = str(hash(password))
data = dumps({'cmd': 'AUTH', 'user': login, 'pswd': hash_password, 'auth': 0, 'error': 0})
self.sendLine(str(data))
def connectionLost(self, reason):
"""
Says to client, why we are close connection
"""
print 'connection lost (protocol)'
def lineReceived(self, data):
"""
Processing responses from serverSSL.py and send new requests to there
"""
new_data = loads(data)
if new_data['cmd'] == 'BBYE':
self.transport.loseConnection()
else:
print new_data
class ServerClientSLLFactory(ClientFactory):
protocol = ServerClientSSL
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
if __name__ == '__main__':
import sys
if len(sys.argv) < 3:
print 'Using: python client_console.py [IP] [PORT] '
else:
ip = sys.argv[1]
port = sys.argv[2]
factory = ServerClientSLLFactory()
reactor.connectSSL(ip, int(port), factory, ssl.ClientContextFactory())
reactor.run()
不要自己编写上下文工厂。请改用
^{pr2}$twisted.internet.ssl.CertificateOptions
。它比你这里的问题少。在__del__
的第一条规则:不要使用__del__
。添加此方法不会自动清除会话。相反,它几乎可以保证您的会话永远不会被清理。协议有一个方法,当它们完成时被调用——它被称为connectionLost
。用这个代替。在Twisted是一个单线程多任务系统。这些语句会阻塞网络I/O和数据库操作。当他们运行时,你的服务器不会做任何其他事情。在
使用} 或alchimia异步执行数据库交互。在
twisted.enterprise.adbapi
或^{有很多协议比} 。更实质性的改进是切换到^{} 。在
LineReceiver
更好。最简单的改进就是切换到^{使用更快的JSON库。不过,在修复应用程序中的阻塞数据库代码之后,我怀疑您还需要一个更快的JSON库。在
^{} 。当你切换到
Int32StringReceiver
或AMP
之后,你就不再需要这个了。在相关问题 更多 >
编程相关推荐