我试图获得最大数量的开放连接到websockets服务器。我用Python编写了简单的代码。这给了我28K的开放连接,但我认为服务器或客户端代码可能有问题。
Server.py
#!/usr/bin/env python
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self):
self.clients.append(self)
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
#self.clients.remove(self)
pass
#print 'closed connection'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application,no_keep_alive=False)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
#!/usr/bin/env python
"""
Connect websockets in concurrency,
each connection should be open until last connection made and
server did not response
"""
import sys
import gevent
from gevent import monkey
from websocket import create_connection
#------------
# Functions
#------------
def send_hello(n):
my_count = 0
while True:
ws = create_connection(ws_link)
ws.send("Hello World")
recv = ws.recv()
if recv:
print "-----------------------"
print "I'm Connection : %r" % n
print "Sending 'Hello World'"
print "Received : %s" % recv
my_count = my_count + 1
#ws.close() # Do not close the connections,
# Let's see how much server can handle..
print "I've sent %r messeges to server" % my_count
print "-----------------------"
if __name__ == '__main__':
if len(sys.argv) != 3:
print "nUsage:nt %r <ws_link> <number_of_connection>n" % sys.argv[0]
sys.exit(1)
ws_link, number_of_connections = sys.argv[1:]
# patches stdlib to cooperate with other greenlets
#monkey.patch_thread()
try:
monkey.patch_all()
jobs = [ gevent.spawn(send_hello,i) for i in range(int(number_of_connections)) ]
gevent.wait(jobs)
except Exception as e:
print "Error : %r" % e
sys.exit(1)
一个问题是您需要一个全局客户列表。您的服务器代码目前有一个客户端列表,每个客户端只包含自己。
:
#!/usr/bin/env python
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
clients = []
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
clients.append(self)
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
clients.remove(self)
pass
#print 'closed connection'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application,no_keep_alive=False)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()