我正在用Python编写一个WebSocket服务器。我已经尝试了txws、autobahn和tornado的方法,但结果都差不多。
使用安全的WebSocket时,我的内存消耗似乎非常大,我无法弄清楚为什么会发生这种情况。下面是一个在tornado中的例子,但我也可以提供在autobahn或txws中的示例。
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import json
class AuthHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection for auth'
def on_message(self, message):
message = json.loads(message)
client_id = message['client_id']
if client_id not in app.clients:
app.clients[client_id] = self
self.write_message('Agent Recorded')
def on_close(self):
print 'auth connection closed'
class MsgHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection for msg'
def on_message(self, message):
message = json.loads(message)
to_client = message['client_id']
if to_client in app.clients:
app.clients[to_client].write_message('You got a message')
def on_close(self):
print 'msg connection closed'
app = tornado.web.Application([
(r'/auth', AuthHandler),
(r'/msg', MsgHandler)
])
app.clients = {}
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(app, ssl_options={
'certfile': 'tests/keys/server.crt',
'keyfile': 'tests/keys/server.key'
})
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start()
在进行了约10,000次连接后,我发现使用SSL时的内存占用量约为700MB,而不使用时仅为43MB,并且除非我杀掉进程,否则它永远不会还回来。似乎问题与建立的连接数量密切相关,而不是发送的消息数量。
这种内存消耗似乎与客户端无关(我编写了自己的客户端并尝试了其他客户端)。
安全Websockets真的比普通Websockets更加内存密集吗?还是我的服务器代码没有正确实现?