本文整理汇总了Python中messenger.Messenger.send方法的典型用法代码示例。如果您正苦于以下问题:Python Messenger.send方法的具体用法?Python Messenger.send怎么用?Python Messenger.send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类messenger.Messenger
的用法示例。
在下文中一共展示了Messenger.send方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: client_thread
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
def client_thread(conn):
current_state = WAITING_TO_START_GAME
messenger = Messenger(conn)
while current_state is not GAME_OVER:
if current_state is WAITING_TO_START_GAME:
game = init_game(messenger)
current_state = WAITING_FOR_MOVE
elif current_state is WAITING_FOR_MOVE:
letter = messenger.read()
if game.already_guessed(letter):
reply = "You've already guessed %r." % letter
else:
game.guess_letter(letter)
reply = str(game)
if game.gameover:
current_state = WAITING_TO_PLAY_AGAIN
messenger.send(reply)
messenger.send(str(game.gameover))
elif current_state is WAITING_TO_PLAY_AGAIN:
play_again = messenger.read()
if play_again == "play":
current_state = WAITING_TO_START_GAME
elif play_again == "quit":
current_state = GAME_OVER
conn.close()
示例2: authenticate_as_client
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
def authenticate_as_client(self, session_socket):
# authenticates an external server connected via session_socket
iv = self.receive_iv(session_socket)
master_encrypter = Encrypter(self.master_key, iv)
m = Messenger(session_socket, master_encrypter, self.continueHandler)
client_challenge = genStr(CHALLENGE_LENGTH)
client_challenge_hash = str(create_key(client_challenge))
hash_len = len(client_challenge_hash)
secretA = generateAorB()
publicA = pow(g, secretA, p)
m.send(client_challenge + str(publicA))
response = m.recv()
while not response:
response = m.recv()
if response[:hash_len] != client_challenge_hash:
m.close()
raise Exception('client could not authenticate')
server_challenge_hash = str(create_key(response[hash_len:hash_len + CHALLENGE_LENGTH]))
m.send(server_challenge_hash)
public_b = int(response[hash_len + CHALLENGE_LENGTH:])
self.log.info('g^b mod p is {}'.format(public_b))
session_key = create_key(str(pow(public_b, secretA, p)))
self.log.info('Session key generated by the client is {}'.format(session_key))
session_encrypter = Encrypter(session_key, iv)
session_m = Messenger(session_socket, session_encrypter, self.continueHandler)
self._messenger = session_m
示例3: check_schedule
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
def check_schedule(self, localtime):
client = Client()
for volume in client.get_volumes():
try:
self._check_volume_schedule(localtime, volume)
except:
error_msg = 'Scheduler failed to check volume schedule. %r' % {
'volume_id': volume.id
}
logger.exception(error_msg)
msg = Messenger(volume)
msg.send('%s\n\n%s' % (error_msg, traceback.format_exc()))
示例4: authenticate_as_server
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
def authenticate_as_server(self, session_socket):
# authenticates an external client connected via session_socket
iv = self.generate_and_send_iv(session_socket) # the server should generate a random iv
master_encrypter = Encrypter(self.master_key, iv)
m_messenger = Messenger(session_socket, master_encrypter, self.continueHandler)
secret_b = generateAorB()
public_b = str(pow(g, secret_b, p))
server_challenge = genStr(CHALLENGE_LENGTH)
server_challenge_hash = str(create_key(server_challenge))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
client_challenge = response[:CHALLENGE_LENGTH]
client_challenge_hash = str(create_key(client_challenge))
public_a = response[CHALLENGE_LENGTH:]
self.log.info('publicA is {}'.format(public_a))
m_messenger.send(client_challenge_hash + server_challenge + public_b)
session_key = create_key(str(pow(int(public_a), secret_b, p)))
self.log.info('session key is {}'.format(session_key))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
if response != server_challenge_hash:
self.log.warn('Client could not be authenticated. Session will be terminated!')
m_messenger.close()
else:
print('Server Authentication Successful!!!')
session_encrypter = Encrypter(session_key, iv)
self._messenger = Messenger(session_socket, session_encrypter, self.continueHandler)
示例5: raw_input
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
if current_state is WAITING_FOR_WELCOME:
print messenger.read()
current_state = WAITING_FOR_BOARD
elif current_state is WAITING_FOR_BOARD:
print messenger.read()
current_state = WAITING_FOR_GAME_STATUS
elif current_state is WAITING_FOR_GAME_STATUS:
msg = messenger.read()
if msg == "True":
current_state = WAITING_TO_PLAY_AGAIN
elif msg == "False":
current_state = WAITING_FOR_USER_INPUT
elif current_state is WAITING_FOR_USER_INPUT:
guess = raw_input("Guess a letter: ").lower()
if len(guess) > 1 or guess not in string.lowercase:
print "Please guess a letter."
else:
messenger.send(guess)
current_state = WAITING_FOR_BOARD
elif current_state is WAITING_TO_PLAY_AGAIN:
play_again = raw_input("Play again? (y/n): ").lower()
if "y" in play_again:
current_state = WAITING_FOR_WELCOME
messenger.send("play")
else:
current_state = GAME_OVER
messenger.send("quit")
print "Thanks for playing!"
sock.close()
示例6: thread_client
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
def thread_client(conn, addr, db_conn, active_clients):
"""
Checks and verifies password/username, and handles adding new
users to the database.
Main client loop Accepts messages from client socket then
broadcasts message to all clients. If the connection is broken
the loop will break, database will be updated(active state).
:param conn: socket objected connected with remote client
:param addr: tuple of the remote clients address and port
:param db_conn: connection to the sqlite3 database containing user-info
"""
length_struct = struct.Struct("!I")
local_messenger = Messenger(conn, length_struct)
lock = _thread.allocate_lock()
verified = False # used to control looping
while not verified: # handle client login/signup credentials
try:
"""
first message received will be a login or sign up attempt
message_type will be "LOGIN" or "SIGNUP"
"""
message = local_messenger.recv()
message_type, username, password = message.split("`", 2)
except ValueError or ConnectionResetError:
print("bad connection at {}".format(addr))
break
# retrieve user info from database. username_check() returns two boolean values
lock.acquire()
username_exists, correct_password = username_check(db_conn, username, password)
lock.release()
# add new users to database
if message_type == "SIGNUP":
if username_exists: # username already taken
local_messenger.send("UNAVAILABLE")
else:
# acquire lock and add user to database and active_clients
lock.acquire()
new_user(db_conn, username, password)
active_clients[username] = conn
lock.release()
local_messenger.send("OK")
verified = True
# login existing users
elif message_type == "LOGIN":
if username_exists and correct_password:
if username not in active_clients: # username is not already signed in
# acquire lock and add username to active_clients
lock.acquire()
active_clients[username] = conn
lock.release()
local_messenger.send("OK")
verified = True
else:
local_messenger.send("USER_ACTIVE") # user is already active
else:
local_messenger.send("BAD") # wrong password or username
while verified:
"""
client will only be verified when an existing username and password have been
submitted, or a new username and password has been created.
verified loop will handle all incoming messages, errors, socket closures
"""
try:
message = local_messenger.recv()
except socket.error or struct.error:
print("bad connection at {}".format(addr))
break
if message:
lock.acquire()
local_messenger.broadcast(active_clients, message)
lock.release()
else:
# empty string signaling connection closed
lock.acquire()
del active_clients[username]
lock.release()
conn.close()
break
# clean up after client disconnects or the connection is broken
if username in active_clients:
lock.acquire()
del active_clients[username]
lock.release()
conn.close()
print("{} DISCONNECTED".format(addr))
示例7: init
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
from messenger import Messenger
from colorama import init
from colorama import Fore, Back, Style
init(autoreset=True)
login_info = open(sys.argv[1]).read().splitlines()
username = login_info[0]
password = login_info[1]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Log in
print "Logging in..."
m = Messenger(username=username, password=password)
print "Logged in!"
while True:
# Get friend to talk to
friend = raw_input("Who do you want to talk to? ")
# Get message to send
message = raw_input("What do you want to tell " + friend + "?")
m.send(friend, message)
# my id: 1326450295
# my id: 1664490365
示例8: App
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
class App(tkinter.Tk):
def __init__(self):
super().__init__()
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.protocol("WM_DELETE_WINDOW", lambda: destroy_all(self.connection, self))
self.title("Chat Client")
self.length_struct = struct.Struct("!I")
self.messenger = Messenger(self.connection, self.length_struct)
self.username = ""
self.password = ""
self.connect = ConnectScreen(self, self.connect_to_server)
self.login = LoginScreen(self, self.check_data)
self.chat = ChatScreen(self, self.handle_out_going)
self.connect.pack()
self.connect.pack_children()
def connect_to_server(self):
"""
Callback for self.connect. Retrieves the user submitted address
and port. Attempts to make connection. If any errors are caught the
connect_message widget will be updated with information about the error.
"""
host_address = self.connect.ip_entry.get()
host_port = self.connect.port_entry.get()
try:
host_port = int(host_port)
self.connection.connect((host_address, host_port))
self.connect.pack_forget()
self.login.pack()
self.login.pack_children()
except ValueError:
self.connect.connect_message.config(text="Invalid Entry For Port\nMust Be an Integer", fg="red")
except ConnectionRefusedError:
self.connect.connect_message.config(text="Server Refused Connection", fg="red")
except socket.gaierror:
self.connect.connect_message.config(text="Invalid Address", fg="red")
def check_data(self, message_type):
"""
Communicates with chat server to verify login information. If the
login or sign up attempt fails a message is displayed on the login
screen.
:param message_type: tells the server whether it is a login attempt
or signup request
"""
self.username = self.login.name_entry.get()
self.password = self.login.pass_entry.get()
# restrict user names to alpha numeric values
if not self.username.isalnum():
self.login.display_message.config(text="Username can only be numbers and letters", fg="red")
return
# format message to be sent
message = "{}`{}`{}".format(message_type, self.username, self.password)
reply = ""
# try communicating with server
try:
self.messenger.send(message)
reply = self.messenger.recv()
except ConnectionResetError or ValueError:
self.login.display_message.config(text="Connection with server lost...restarting", fg="red")
self.login.pack_forget()
self.connection.detach()
self.connect.pack()
# check for all possible server responses
if reply == "OK":
self.login.pack_forget()
self.title(self.username)
self.chat.pack()
self.chat.pack_children()
self.connection.settimeout(.10) # prevents blocking calls of handle_incoming()
self.handle_incoming()
elif reply == "UNAVAILABLE":
self.login.display_message.config(text="Username Unavailable", fg="red")
elif reply == "BAD":
self.login.display_message.config(text="Incorrect user Info", fg="red")
elif reply == "USER ACTIVE":
self.login.display_message.config(text="Username is currently already logged in", fg="red")
else:
self.login.display_message.config(text="Unexpected Server Response")
def handle_out_going(self, event=None):
"""
reads from the chat_entry and sends it to the server.
:param event: is used as a place holder for the event
information sent by self.chat_entry.bind(<RETURN>) it is not
used.
"""
text = self.chat.chat_entry.get()
#.........这里部分代码省略.........
示例9: Registry
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
class Registry(object):
"""
Hub of-sorts to talk with different `Cosmid` related files and resources. Can
be seen as the API endpoint for `Cosmid`.
"""
def __init__(self):
super(Registry, self).__init__()
# Set up YAML parser for optional config file
self.config_path = path("cosmid.yaml")
self.config = ConfigReader(self.config_path)
# Extract stuff from config
self.email = self.config.find("email")
# Path to resource storage directory
self.directory = path(self.config.find("directory", default="resources"))
# Load history file consisting of already downloaded resources
self.history_path = path(self.directory + "/.cosmid.yaml")
self.history = HistoryReader(self.history_path)
# Set up a :class:`cosmid.messenger.Messenger`
self.messenger = Messenger("cosmid")
def get(self, resource_id, type_="class"):
"""
<public> Returns an instance of the specified resource class. Dodges an
``ImportError`` when failing to import a resource and returns ``None``
instead.
.. code-block:: python
>>> resource = registry.get("ccds")
>>> resource.latest()
'Hs104'
:param str resource_id: The resource key (name of module)
:returns: A class instance of the resource
"""
try:
if type_ == "class":
return load_class("cosmid.resources.{}.Resource".format(resource_id))()
elif type_ == "module":
return importlib.import_module("cosmid.resources." + resource_id)
else:
raise ValueError("Argument must be either 'class' or 'module'.")
except ImportError:
return None
def grab(self, resource_id, target, collapse=False):
"""
<public> Returns all that's nessesary to download a specific resource.
The method will try to correct both ``resource_id`` and the ``target``
release tag.
:param str resource_id: What resource to download
:param str target: What release of the resource to download
"""
# Either import resource class or print warning and move on.
# Test matching the resource ID
options = [item[0] for item in self.ls()]
resource_id = self.matchOne(resource_id, options)
if resource_id is None:
message = "Couldn't match resource ID: '{}'".format(resource_id)
self.messenger.send("warning", message)
return None, None, None, None
# Get the resource
resource = self.get(resource_id)
# Now let's figure out the version
# No specified version will match to the latest resource release
if target == "latest":
version = resource.latest()
else:
options = resource.versions()
version = self.matchOne(target, options)
if version is None:
message = ("Couldn't match version '{id}#{v}'; {vers}"
.format(v=target, id=resource.id, vers=", ".join(options)))
self.messenger.send("warning", message)
return None, None, None, None
# Get the goahead! (that we haven't already downloaded it)
if self.goahead(resource, version):
# Finally we can determine the paths to download and save the files
dl_paths = resource.paths(version)
if collapse:
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from messenger import Messenger [as 别名]
# 或者: from messenger.Messenger import send [as 别名]
class SessionManager:
def __init__(self, port, ip_address, secret_value, continueHandler):
# can be either a server or client. if ip_address=None, be a server on port. Otherwise, try to connect to
# ip_address:port
self.port = port
self.ip_address = ip_address
self.master_key = create_key(secret_value)
self.log = logging.getLogger(__name__)
self.continueHandler = continueHandler
self._messenger = None
self.reset_messenger()
def generate_and_send_iv(self, session_socket):
iv = urandom(16)
self.continueHandler(iv)
# send iv over socket first!
sent_len = 0
while sent_len < len(iv):
sent = session_socket.send(iv[sent_len:])
if sent == 0:
raise RuntimeError("socket send connection issue")
sent_len += sent # how much of the message we have sent
logging.getLogger(__name__).info("sent iv: " + str(iv))
return iv
def receive_iv(self, session_socket):
iv = b''
while len(iv) < IV_LENGTH:
chunk = session_socket.recv(IV_LENGTH - len(iv))
if chunk == b'':
session_socket.close()
raise RuntimeError("socket closed")
iv += chunk
logging.getLogger(__name__).info('received iv: {}'.format(str(iv)))
return iv
def authenticate_as_server(self, session_socket):
# authenticates an external client connected via session_socket
iv = self.generate_and_send_iv(session_socket) # the server should generate a random iv
master_encrypter = Encrypter(self.master_key, iv)
m_messenger = Messenger(session_socket, master_encrypter, self.continueHandler)
secret_b = generateAorB()
public_b = str(pow(g, secret_b, p))
server_challenge = genStr(CHALLENGE_LENGTH)
server_challenge_hash = str(create_key(server_challenge))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
client_challenge = response[:CHALLENGE_LENGTH]
client_challenge_hash = str(create_key(client_challenge))
public_a = response[CHALLENGE_LENGTH:]
self.log.info('publicA is {}'.format(public_a))
m_messenger.send(client_challenge_hash + server_challenge + public_b)
session_key = create_key(str(pow(int(public_a), secret_b, p)))
self.log.info('session key is {}'.format(session_key))
response = m_messenger.recv()
while not response:
response = m_messenger.recv()
if response != server_challenge_hash:
self.log.warn('Client could not be authenticated. Session will be terminated!')
m_messenger.close()
else:
print('Server Authentication Successful!!!')
session_encrypter = Encrypter(session_key, iv)
self._messenger = Messenger(session_socket, session_encrypter, self.continueHandler)
def authenticate_as_client(self, session_socket):
# authenticates an external server connected via session_socket
iv = self.receive_iv(session_socket)
master_encrypter = Encrypter(self.master_key, iv)
m = Messenger(session_socket, master_encrypter, self.continueHandler)
client_challenge = genStr(CHALLENGE_LENGTH)
client_challenge_hash = str(create_key(client_challenge))
hash_len = len(client_challenge_hash)
secretA = generateAorB()
publicA = pow(g, secretA, p)
m.send(client_challenge + str(publicA))
response = m.recv()
while not response:
response = m.recv()
if response[:hash_len] != client_challenge_hash:
m.close()
raise Exception('client could not authenticate')
server_challenge_hash = str(create_key(response[hash_len:hash_len + CHALLENGE_LENGTH]))
#.........这里部分代码省略.........