本文整理汇总了Python中websocket_server.WebsocketServer.run_forever方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketServer.run_forever方法的具体用法?Python WebsocketServer.run_forever怎么用?Python WebsocketServer.run_forever使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websocket_server.WebsocketServer
的用法示例。
在下文中一共展示了WebsocketServer.run_forever方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def start_server(port):
server = WebsocketServer(port)
ws_log.debug("Server listening on port: %d" % port)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
server.run_forever()
示例2: start_wss
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def start_wss(port):
"start the websocket test server"
def reply_back(client, server, msg):
server.send_message(client, "You sent: %s" % msg)
server = WebsocketServer(port)
server.set_fn_message_received(reply_back)
server.run_forever()
示例3: WsLapCounterServerLaunch
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def WsLapCounterServerLaunch():
global wsLapCounterServer
while 1:
try:
wsLapCounterServer = WebsocketServer( port=PORT_NUMBER + 2, host='' )
wsLapCounterServer.set_fn_new_client( lap_counter_new_client )
wsLapCounterServer.run_forever()
except Exception as e:
wsLapCounterServer = None
time.sleep( 5 )
示例4: WsServerLaunch
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def WsServerLaunch():
global wsServer
while 1:
try:
wsServer = WebsocketServer( port=PORT_NUMBER + 1, host='' )
wsServer.set_fn_message_received( message_received )
wsServer.run_forever()
except Exception as e:
wsServer = None
time.sleep( 5 )
示例5: listen
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def listen(courier, host, port):
server = WebsocketServer(port)
server.set_fn_new_client(notify_client)
uthread = threading.Thread(target=updater, args=(courier, server))
tthread = threading.Thread(target=v_timer, args=(server,))
uthread.daemon = True
tthread.daemon = True
uthread.start()
tthread.start()
print("Starting WebSocket Server...")
server.run_forever()
示例6: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def start_server():
"""Start both the Game Manager and the Web Server"""
# Prepare the web server with above functions
logger.info("Init Web Socket Server")
server = WebsocketServer(PORT, HOST)
server.set_fn_new_client(onconnect)
server.set_fn_client_left(ondisconnect)
server.set_fn_message_received(onmessage)
# Create a game manager
logger.info("Init Game Manager")
global manager
manager = Manager(server)
# Start the web server
logger.info("Starting Server")
server.run_forever()
manager.safe_stop()
示例7: IPCWebSocket
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
class IPCWebSocket(object):
def __init__(self, ipc):
self.ipc = ipc
self.server = WebsocketServer(9000)
self._set_callbacks(self.server)
self.clients = []
def start(self):
from threading import Thread
def run():
self.server.run_forever()
t = Thread(target=run)
t.daemon = True
t.start()
def _set_callbacks(self, server):
server.set_fn_new_client(self.on_connect)
server.set_fn_client_left(self.on_disconnect)
server.set_fn_message_received(self.on_message)
def on_connect(self, client, server):
print("New client connected")
self.clients.append(client)
def on_disconnect(self, client, server):
print("Client disconnected")
self.clients = [c for c in self.clients if c['id'] != client['id']]
def on_message(self, client, server, message):
message = json.loads(message)
self.ipc.on_message(client, message)
def broadcast(self, message):
message = json.dumps(message)
for c in self.clients:
self.server.send_message(c, message)
print("broadcasted message to {} clients".format(len(self.clients)))
def send(self, client, message):
self.server.send_message(client, json.dumps(message))
示例8: webServer
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
#.........这里部分代码省略.........
print("Client(%d) disconnected" % client['id'])
def message_received(client, server, message):
#print("received message from client id %d " % client['id'])
#logging.info("received message from client id %d " % client['id'])
msg = json.loads(message)
if msg["action"] == AUTHENTICATE:
print 'msg is AUTHENTICATE'
resp = {"action": AUTHENTICATE, "data": None}
username = msg["data"].get("username") if msg["data"].has_key("username") else None
password = msg["data"].get("password") if msg["data"].has_key("password") else None
if username and password and users.has_key(username) and password == users[username]:
print "AUTHSUCCESS"
resp["data"] = AUTHSUCCESS
else:
print "AUTHFAIL"
resp["data"] = AUTHFAIL
server.send_message(client, json.dumps(resp) )
elif msg["action"] == GETBANNEDIPs:
#print 'msg is GETBANNEDIPs'
#logging.info('msg is GETBANNEDIPs')
resp = {"action": GETBANNEDIPs, "data": []}
username = msg["data"].get("username") if msg["data"].has_key("username") else None
password = msg["data"].get("password") if msg["data"].has_key("password") else None
if username and password and users.has_key(username) and password == users[username]:
for bannedIP in bannedIPs.values():
ip = {}
ip["IP"] = bannedIP.IP
ip["time"] = time.strftime("%b %d %H:%M:%S", time.localtime(bannedIP.time))
ip["timer"] = bannedIP.timer - (time.time() - bannedIP.time)
ip["service"] = bannedIP.service
resp["data"].append(ip)
server.send_message(client, json.dumps(resp))
else:
print "AUTHFAIL"
resp["data"] = AUTHFAIL
server.send_message(client, json.dumps(resp))
elif msg["action"] == GETFAILEDATTEMPTs:
print 'msg is GETFAILEDATTEMPTs'
resp = {"action": GETFAILEDATTEMPTs, "data": []}
username = msg["data"].get("username") if msg["data"].has_key("username") else None
password = msg["data"].get("password") if msg["data"].has_key("password") else None
if username and password and users.has_key(username) and password == users[username]:
for failedAttempt in failedAttempts:
print "in FA"
print "FA=" + str(failedAttempt)
ip = {}
ip["IP"] = failedAttempt[0]
ip["attempts"] = []
ip["service"] = failedAttempt[1]
for attempt in failedAttempts[failedAttempt]:
ip["attempts"].append(time.strftime("%b %d %H:%M:%S", time.localtime(attempt.time)))
resp["data"].append(ip)
server.send_message(client, json.dumps(resp))
else:
print "AUTHFAIL"
resp["data"] = AUTHFAIL
server.send_message(client, json.dumps(resp))
elif msg["action"] == UNBANIPs:
print 'msg is UNBANIPs'
resp = {"action": UNBANIPs, "data": {}}
username = msg["data"].get("username") if msg["data"].has_key("username") else None
password = msg["data"].get("password") if msg["data"].has_key("password") else None
if username and password and users.has_key(username) and password == users[username]:
unbanIP(msg["data"]["IP"], msg["data"]["service"])
resp["data"]["IP"] = msg["data"]["IP"]
resp["data"]["service"] = msg["data"]["service"]
server.send_message(client, json.dumps(resp))
else:
print "AUTHFAIL"
resp["data"] = AUTHFAIL
server.send_message(client, json.dumps(resp))
elif msg["action"] == CHANGECONFIG:
print 'msg is CHANGECONFIG'
#changeconfig(bantimer,nofailedattempts,failinterval)
data = msg["data"]
for service in services.values():
if service.name.lower() == data.get("service").lower():
changeConfig(data.get("bantimer"), data.get("threshold"), data.get("interval"), service)
#server.send_message(client, json.dumps(resp))
global server
PORT=9001
server = WebsocketServer(PORT, host='0.0.0.0')
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
server.run_forever()
示例9: WebsocketServer
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
server = WebsocketServer(PORT)
manager = Manager(server)
# Called for every client connecting (after handshake)
def new_client(client, server):
print("New client connected and was given id %d" % client['id'])
# Called for every client disconnecting
# @manager.user_logout
def client_left(client, server):
manager.user_logout(client)
print("Client disconnected")
# Called when a client sends a message
# @status_check
@manager.check_message
def message_received(client, server, message):
print(message)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
# clear all LoggedUsers
MenuUser.objects.all().delete()
# then run server
server.run_forever()
示例10: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
class WSServer:
def __init__(self, port=9007):
self.port = port
self.server = WebsocketServer(self.port, host='0.0.0.0')
self.server.set_fn_new_client(self.on_connect)
self.server.set_fn_message_received(self.on_msg)
self.server.set_fn_client_left(self.on_disconnect)
self.msg_lock = Lock()
def ping(self):
self.server.send_message_to_all(json.dumps({'action': 'ping'}))
# pinging every 50 seconds to avoid disconnection
t = Timer(50, self.ping)
t.start()
def on_connect(self, client, server):
#server.send_message_to_all("Hey all, a new client has joined us")
pass
def on_disconnect(self, client, server):
#server.send_message_to_all("Hey all, a new client has joined us")
pass
def on_msg(self, client, server, message):
self.msg_lock.acquire()
try:
args = message.split(' ')
command = args[0]
args = args[1:]
internal = 'internal_ws_' + command
if hasattr(self, internal):
getattr(self, internal)(client, *args)
else:
data = {'action': 'cmd', 'msg': 'not found'}
self.server.send_message(client, json.dumps(data))
except Exception as e:
print("Error: ", e)
connection.close()
self.msg_lock.release()
def run(self):
self.ping()
self.server.run_forever()
def drop_seat(self, hold):
session = hold.session
layout = hold.layout
row, col = hold.seat.split('-')
data = {
'action': 'drop',
'session': session.id,
'layout': layout.id,
'row': row,
'col': col,
}
hold.delete()
confirmed = not session.is_seat_available(layout, row, col)
if confirmed:
data['action'] = 'confirm'
self.server.send_message_to_all(json.dumps(data))
def notify_confirmed(self):
d = timezone.now()
d = d - datetime.timedelta(seconds=80)
holds = TicketSeatHold.objects.filter(date__gt=d, type="R")
for h in holds:
row, col = h.seat.split('-')
data = {
'action': 'confirm',
'session': h.session.id,
'layout': h.layout.id,
'row': row,
'col': col,
}
self.server.send_message_to_all(json.dumps(data))
# Protocol definitions
def internal_ws_autoseats(self, client, session, amount, user):
session = Session.objects.get(id=session)
seats = search_seats(session, int(amount))
data = {
'action': 'autoseat',
'session': session.id,
'seats': seats,
}
for s in seats:
layout = SeatLayout.objects.get(id=s['layout'])
seat = '{}-{}'.format(s['row'], s['col'])
d2 = {
'action': 'hold',
'session': session.id,
#.........这里部分代码省略.........
示例11: connecting
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
class websocketserver:
cameras = {}
tags = {}
users = {}
calibration = {}
port=8001
# Called for every client connecting (after handshake)
def new_client_connection(self, client, server):
print("New client connected and was given id %d" % client['id'] +" and address " + str(client['address']))
server.send_message(client, "Client connected succesfully")
# Called for every client disconnecting
def client_left(self, client, server):
print("Client(%d) disconnected" % client['id'])
#TODO : Remove from list
# Called when a client sends a message
def message_received(self, client, server, message):
# print("Client(%d) said: %s" % (client['id'], message))
self.parseMessage(client, message)
def __init__(self, host='127.0.0.1'):
self.server = WebsocketServer(self.port, host)
self.server.set_fn_new_client(self.new_client_connection)
self.server.set_fn_client_left(self.client_left)
self.server.set_fn_message_received(self.message_received)
self.server.run_forever()
def parseMessage(self, client, message):
"""
Check who is the message from to redirect it to User / Tag / Camera / Calibration
or create a new instance of User / Tag / Camera / Calibration
:param client:
:param message:
:return:
"""
if self.cameras.has_key(str(client['address'])):
#print "Message from Camera"
self.cameras[str(client['address'])].push(message)
elif self.users.has_key(str(client['address'])):
print "Message from User"
elif self.tags.has_key(str(client['address'])):
print "Message from Tag"
elif self.calibration.has_key(str(client['address'])):
self.calibration[str(client['address'])].push(message)
print "Message from Calibration"
# This message is coming from an unknown client
else:
if message.split("-")[0] == "camera":
self.cameras[str(client['address'])] = Camera(client, message.split("-")[1])
# Add Observers linking every user to every camera's update
for key in self.users:
if isinstance(self.users[key], User):
self.cameras[str(client['address'])].new2DPointNotifier.addObserver(self.users[key].position.newPoint2DObserver)
self.cameras[str(client['address'])].point2DdeletedNotifier.addObserver(self.users[key].position.point2DDeletedObserver)
elif message.split("-")[0] == "tag":
print "Hello TAG"
# TODO
elif message.split("-")[0] == "user":
user = User(client, self.server, message.split("-")[1])
self.users[str(client['address'])] = user
# Add Observers linking every user to every camera's update
for key in self.cameras:
if isinstance(self.cameras[key], Camera):
self.cameras[key].new2DPointNotifier.addObserver(user.position.newPoint2DObserver)
self.cameras[key].point2DdeletedNotifier.addObserver(user.position.point2DDeletedObserver)
elif message == "calibration":
self.calibration[str(client['address'])] = Calibration(self.cameras, self.server, client)
示例12: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def __init__(self, host='127.0.0.1'):
server = WebsocketServer(self.port, host)
server.set_fn_new_client(self.new_client_connection)
server.set_fn_client_left(self.client_left)
server.set_fn_message_received(self.message_received)
server.run_forever()
示例13: serve
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def serve(port, host):
from websocket_server import WebsocketServer
from threading import Thread, Event
import signal
def message_received(client, server, message):
print 'message_received:', message
cmds = message.split('|')
for cmd in cmds:
if cmd.startswith('addr='):
address = cmd[5:]
if server.watched_addresses.has_key(address):
server.watched_addresses[address].append(client)
else:
server.watched_addresses[address] = [client]
if cmd == 'blocks':
server.block_watchers.append(client)
def client_left(client, server):
print 'client_left:', client
addrs = []
for key in server.watched_addresses:
if client in server.watched_addresses[key]:
addrs.append(key)
for addr in addrs:
clients = server.watched_addresses[addr]
clients.remove(client)
if not clients:
del server.watched_addresses[addr]
if client in server.block_watchers:
server.block_watchers.remove(client)
def service_thread(ws_server, evt):
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from bitrisk.bitcoind_config import read_default_config
import json
import decimal
config = read_default_config()
testnet = ''
if config.has_key('testnet'):
testnet = config['testnet']
rpc_user = config['rpcuser']
rpc_password = config['rpcpassword']
rpc_connection = AuthServiceProxy("http://%s:%[email protected]%s:%s8332"%(rpc_user, rpc_password, host, testnet))
conn = sqlite3.connect(db_filename)
while not evt.wait(5):
txs = get_db_txs(conn)
for tx in txs:
print 'tx:', tx
tx = rpc_connection.gettransaction(tx)
for details in tx['details']:
addr = details['address']
if ws_server.watched_addresses.has_key(addr):
def decimal_default(obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
raise TypeError
msg = json.dumps(tx, default=decimal_default)
for client in ws_server.watched_addresses[addr]:
ws_server.send_message(client, msg)
blocks = get_db_blocks(conn)
for block in blocks:
print 'block:', block
for client in ws_server.block_watchers:
ws_server.send_message(client, block)
server = WebsocketServer(port, host)
server.watched_addresses = {}
server.block_watchers = []
server.set_fn_message_received(message_received)
server.set_fn_client_left(client_left)
evt = Event()
thread = Thread(target=service_thread, args=(server, evt))
thread.start()
server.run_forever() # catches and exits on SIGINT
evt.set() # stop service_thread
thread.join()
示例14: signal_handler
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
def signal_handler(signal, frame):
print('\nShutting down server..')
global carIsConnected
global runServer
carConnectionSem.acquire()
runServer = False
# If car is not connected: connect to self as car then close connection
# so thread will continue and check if it needs to stop
if(not carIsConnected):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1',carPort))
s.close()
carConnectionSem.release()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Start car communication thread
t = threading.Thread(target=communicateWithCar)
threads.append(t)
t.start()
print 'Listening on port', carPort, 'for car'
# Start websocket to communicate with client
websocket.run_forever()
示例15: connecting
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import run_forever [as 别名]
class websocketserver:
cameras = {}
tags = {}
users = {}
calibration = {}
port=8001
# Called for every client connecting (after handshake)
def new_client_connection(self, client, server):
print("New client connected and was given id %d" % client['id'] +" and address " + str(client['address']))
server.send_message(client, "Client connected succesfully")
# Called for every client disconnecting
def client_left(self, client, server):
print("Client(%d) disconnected" % client['id'])
# Remove client from its list
# TODO better delete (remove points etc...)
if(str(client['address']) in self.cameras):
print "Camera disconnected : " + str(client['address'])
del self.cameras[str(client['address'])]
elif(str(client['address']) in self.users):
# Remove Tag assignement because User left
print "User disconnected : " + str(client['address'])
self.users[str(client['address'])].removeTag()
del self.users[str(client['address'])]
elif(str(client['address']) in self.calibration):
print "Calibration disconnected : " + str(client['address'])
del self.calibration[str(client['address'])]
elif(str(client['address']) in self.tags):
print "Tag disconnected : " + str(client['address'])
# Remove Tag assignement to User because Tag left AND kill 3D point
for key in self.users:
if self.users[key].tag == self.tags[str(client['address'])]:
self.users[key].removeTag()
del self.tags[str(client['address'])]
# Called when a client sends a message
def message_received(self, client, server, message):
self.parseMessage(client, message)
def __init__(self, host='127.0.0.1'):
self.server = WebsocketServer(self.port, host)
self.server.set_fn_new_client(self.new_client_connection)
self.server.set_fn_client_left(self.client_left)
self.server.set_fn_message_received(self.message_received)
self.server.run_forever()
def parseMessage(self, client, message):
"""
Check who is the message from to redirect it to User / Tag / Camera / Calibration
or create a new instance of User / Tag / Camera / Calibration
:param client:
:param message:
:return:
"""
if self.cameras.has_key(str(client['address'])):
#print "Message from Camera"
self.cameras[str(client['address'])].push(message)
# Update all cameras counters
#Todo: Change this method for checking all cameras for lost point (auto check inside point2D ?)
for key in self.cameras.keys():
self.cameras[key].update()
elif self.users.has_key(str(client['address'])):
print "Message from User"
elif self.tags.has_key(str(client['address'])):
print "Message from Tag"
elif self.calibration.has_key(str(client['address'])):
self.calibration[str(client['address'])].push(message)
print "Message from Calibration"
# This message is coming from an unknown client
else:
if message.split("-")[0] == "camera":
self.cameras[str(client['address'])] = Camera(client, message.split("-")[1])
# Add Observers linking every user to every camera's update
for key in self.users:
if isinstance(self.users[key], User):
self.cameras[str(client['address'])].new2DPointNotifier.addObserver(self.users[key].position.newPoint2DObserver)
self.cameras[str(client['address'])].point2DdeletedNotifier.addObserver(self.users[key].position.point2DDeletedObserver)
elif message.split("-")[0] == "tag":
self.tags[str(client['address'])] = Tag(self.server, client, message.split("-")[1])
for key in self.users:
if isinstance(self.users[key], User):
# Assign a Tag to User with no Tag
if self.users[key].tag == None:
self.users[key].setTag(self.tags[str(client['address'])])
#.........这里部分代码省略.........