本文整理汇总了Python中websocket_server.WebsocketServer.set_fn_new_client方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketServer.set_fn_new_client方法的具体用法?Python WebsocketServer.set_fn_new_client怎么用?Python WebsocketServer.set_fn_new_client使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websocket_server.WebsocketServer
的用法示例。
在下文中一共展示了WebsocketServer.set_fn_new_client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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_new_client [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: WsLapCounterServerLaunch
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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: listen
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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()
示例5: start_server
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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()
示例6: nuevo_cliente
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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_new_client [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_new_client [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_new_client [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: connecting
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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'])])
#.........这里部分代码省略.........
示例11: now
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [as 别名]
query_string = """ SELECT value FROM "error_rate" WHERE "session_id" = '{session_id}' AND time >= now() - 10s AND time <= now() """.format(session_id=session_id)
result = influx_client.query(query_string)
if result:
print("Sending messages...")
else:
print("No message found!")
c = 1
if "counter" in client:
c = int(client["counter"])
for items in result:
for item in items:
server.send_message_to_all("Batch Number => " + str(c))
server.send_message_to_all("Error Rate => " + str(item['value']))
c+=1
sleep(0.045)
else:
server.send_message_to_all("Session expired..!")
def receive_messages(client,server, message):
client['counter'] = message
send_messages(client, server)
server = WebsocketServer(8080, host='0.0.0.0')
server.set_fn_new_client(send_messages)
server.set_fn_message_received(receive_messages)
server.run_forever()
示例12: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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: doLogin
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [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()
示例14: print
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [as 别名]
carConnectionSem.release()
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()
示例15: WebsocketPublisher
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import set_fn_new_client [as 别名]
class WebsocketPublisher(object):
"""
Publish cluster state as JSON over a websocket.
Only sends CS state, and information on who is building on who.
This is enough information to draw a graph of the cluster.
Explicitly, does not send information on individual jobs.
"""
MIN_SEND_GAP_S = 0.1
"""Minimum gap in seconds between sending messages to connected clients."""
def __init__(self, host="0.0.0.0", port=9999):
self.frame = ""
self.nodes = ""
self.links = ""
self.last_sent_frame = ""
self.last_sent_nodes = ""
self.last_sent_links = ""
self.next_time_to_send = 0
self.lock = threading.RLock()
self.timer = None
self.ws_server = WebsocketServer(port, host)
def send_to_client(client, server):
with self.lock:
server.send_message(client, self.build_graph(True))
self.ws_server.set_fn_new_client(send_to_client)
t = threading.Thread(target=self.ws_server.run_forever)
t.daemon = True
t.start()
def build_nodes(self, mon):
"""Builds a JSON representation of the CS nodes in the cluster."""
nodes = []
for cs in mon.cs.values():
nodes.append({"id": cs.id,
"name": cs.name,
"ip": cs.ip,
"load": (100*cs.active_jobs())/cs.maxjobs})
return json.dumps(nodes)
def build_links(self, mon):
"""
Builds a JSON representation of the links in the cluster.
There is one link A->B if A has one or more jobs building on B.
"""
links = []
for job in mon.jobs.values():
if job.host_id not in mon.cs or job.client_id not in mon.cs:
continue
c, s = mon.cs[job.client_id], mon.cs[job.host_id]
# Don't double-add links.
add = True
for l in links:
if l["source"] == c.id and l["target"] == s.id:
add = False
if add:
links.append({"source": c.id, "target": s.id, "value": 10})
return json.dumps(links)
def build_graph(self, full=False):
"""Builds a full JSON representation of a graph of the cluster."""
frame = '{"timestamp": 0, "index": 0'
if full or self.nodes != self.last_sent_nodes:
frame += ', "nodes": ' + self.nodes
if full or self.links != self.last_sent_links:
frame += ', "links": ' + self.links
frame += '}'
return frame
def publish(self, mon):
"""
Called by the Monitor to indicate new cluster state.
Update our internal state, and notify clients if appropriate.
"""
with self.lock:
self.nodes = self.build_nodes(mon)
self.links = self.build_links(mon)
self.frame = self.build_graph()
self.notify()
def notify(self):
"""Send updates to clients if necessary."""
now = time.time()
with self.lock:
if self.frame == self.last_sent_frame:
# Frame hasn't changed, don't resend.
#.........这里部分代码省略.........