本文整理汇总了Python中websocket_server.WebsocketServer.set_fn_client_left方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketServer.set_fn_client_left方法的具体用法?Python WebsocketServer.set_fn_client_left怎么用?Python WebsocketServer.set_fn_client_left使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websocket_server.WebsocketServer
的用法示例。
在下文中一共展示了WebsocketServer.set_fn_client_left方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
def __init__(self, conf):
global server
super(WSService, self).__init__()
self.conf = conf
server = WebsocketServer(WSPORT, host='0.0.0.0')
server.set_fn_new_client(newClient)
server.set_fn_client_left(leftClient)
示例3: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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()
示例4: webServer
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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()
示例5: runWebsocketServer
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
# 6. Send Khan user data to the client
#server.send_message(client, login_data)
def runWebsocketServer():
global server
server.run_forever()
def runAuthServer():
global callback_server
callback_server.serve_forever()
#PORT=9001
PORT=8080
SERVERHOST= "0.0.0.0"
server = WebsocketServer(PORT, SERVERHOST)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
#server.run_forever()
#callback_server.serve_forever()
t1 = threading.Thread(target=runWebsocketServer, args=[])
t2 = threading.Thread(target=runAuthServer, args=[])
t1.start()
t2.start()
示例6: nuevo_cliente
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
#!/usr/bin/env python
from websocket_server import WebsocketServer
import hashlib
import os
def nuevo_cliente(client, server):
print("Cliente (%s) nuevo" % client['address'][0])
def mensaje_recibido(client, server, mensaje):
audio = hashlib.md5(client['address'][0]).hexdigest()
file = open("podcast/"+audio, "ab")
file.write(mensaje)
file.close()
def desconectado(client, server):
audio = hashlib.md5(client['address'][0]).hexdigest()
os.remove("podcast/"+audio)
print("Cliente (%s) desconectado" % client['address'][0])
PORT=9000
server = WebsocketServer(PORT,"192.168.1.2")
server.set_fn_new_client(nuevo_cliente)
server.set_fn_client_left(desconectado)
server.set_fn_message_received(mensaje_recibido)
server.run_forever()
示例7: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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,
#.........这里部分代码省略.........
示例8: GetModuleName
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
for mod in modlist:
mname = GetModuleName(phandle,mod)
if mname.endswith(game["moduleName"]):
memory_address = mod + game["memoryOffset"]
# read address
def readTicker():
ReadProcessMemory(phandle, memory_address, ticker, ticker_s, byref(bytesRead))
def clientJoin(client,server):
global client_num
client_num += 1
if(client_num==1):
initTicker()
def clientLeave(client,server):
global client_num
client_num -= 1
if(client_num==0):
CloseHandle(phandle)
def clientMsg(client,server,message):
readTicker()
server.send_message(client,ticker.value.replace('m','.'))
print "Starting server on " + str(socket.gethostbyname(socket.gethostname()))
server = WebsocketServer(config["serverPort"],"0.0.0.0")
server.set_fn_new_client(clientJoin)
server.set_fn_client_left(clientLeave)
server.set_fn_message_received(clientMsg)
server.run_forever()
示例9: connecting
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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)
示例10: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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()
示例11: doLogin
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
def doLogin(message, server):
global unModel
# obj = ast.literal_eval(message) //pour compatibilité avec Android
# print message //aucune idée pourquoi mais il faut mettre cela pour que ça fonctionne avec Android!!?
obj = json.loads(message)
objLogin = obj["object"]
unModel.nom = objLogin["name"]
unModel.prenom = objLogin["firstname"]
#Ack client
dict={}
dict["messageType"]="ackLogin"
objJson = json.dumps(dict)
server.send_message(wsIHM, objJson)
if __name__ == "__main__":
# Fixation du point de lecture de fichier
os.chdir('/')#Obligation de donner le chemin du fichier avec le QPython
# routage des messages receptionnes
switch={
"login":doLogin
}
# Initialisation des models
unModel = UnModel()
# Connexion au client web
server = WebsocketServer(9999)
server.set_fn_new_client(new_client) #définition de la fonction pour l arrivé d un nouveau client
server.set_fn_message_received(rxMessage) #Définition de la fonction pour l arrivé d un nouveau message
server.set_fn_client_left(clientLeft) #définition de la fonction pour la déconnexion d'un client
server.run_forever()
示例12: serve
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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()
示例13: print
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [as 别名]
print('Client disconnected')
# Receive data from client and put it in the input queue
def communicateWithClient(client, server, msg):
print('recv: ' + msg)
carConnectionSem.acquire()
if (carIsConnected and msg in validInput):
inputSem.acquire()
inputQueue.append(msg)
inputSem.release()
carConnectionSem.release()
# Websocket to talk to client
websocket = WebsocketServer(clientPort)
websocket.set_fn_new_client(onClientConnection)
websocket.set_fn_client_left(onClientDisconnection)
websocket.set_fn_message_received(communicateWithClient)
# Handle car communications
def communicateWithCar():
while(runServer):
# Wait for car to connect
c, addr = carSock.accept()
isConnected = True
global carIsConnected
carConnectionSem.acquire()
carIsConnected = True
carConnectionSem.release()
print('Car connected')
示例14: connecting
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_client_left [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'])])
#.........这里部分代码省略.........