本文整理汇总了Python中connection.Connection.recv方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.recv方法的具体用法?Python Connection.recv怎么用?Python Connection.recv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.recv方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import recv [as 别名]
class Bot:
def __init__(self, config):
self.config = config
self.state = STATE.DISCONNECTED
self.conn = None
self.last_recv = None
self.awaiting_pong = False
self.handlers = {
'PING': self.handle_ping,
'376': self.handle_motd, # RPL_ENDOFMOTD
'422': self.handle_motd, # ERR_NOMOTD
'NOTICE': self.handle_notice,
'MODE': self.handle_mode,
'PRIVMSG': self.handle_privmsg,
}
self.scripts = defaultdict(list)
def __str__(self):
return '<Bot: %s/%s>' % (self.config.host, self.config.nick)
def exception(self, line):
exc_type, exc_value, exc_tb = sys.exc_info()
exc_list = traceback.format_exception(exc_type, exc_value, exc_tb)
self.log(line + '\n' + ''.join(exc_list))
path, lineno, method, code = traceback.extract_tb(exc_tb)[-1]
path = os.path.relpath(path)
exc_name = exc_type.__name__
notice = '%s:%s():%d %s: %s' % (path, method, lineno, exc_name, exc_value)
if code is not None:
notice += ' | ' + code[:50]
self.notice(config.settings['owner'], notice)
def log(self, text):
log.write('%s/%s: %s' % (self.config.host, self.config.nick, text))
def connect(self):
host = self.config.host
port = self.config.port
self.log('connecting to port %d...' % port)
self.last_recv = time.time()
self.awaiting_pong = False
if not self.conn:
self.conn = Connection()
fd, error = self.conn.connect(host, port)
if error:
self.log(error)
self.state = STATE.DISCONNECTED
else:
self.state = STATE.CONNECTING
self.handle_notice(None)
return fd
def handle(self):
for line in self.conn.recv():
msg = ServerMessage(line)
handler = self.handlers.get(msg.command)
if handler:
try:
handler(msg)
except:
self.exception(line)
self.last_recv = time.time()
def check_disconnect(self, ts):
time_since = ts - self.last_recv
ping_timeout_wait = config.PING_INTERVAL + config.PING_TIMEOUT
if time_since > ping_timeout_wait:
self.log('no reply from server in %ds' % ping_timeout_wait)
self.disconnect()
return True
elif time_since > config.PING_INTERVAL and not self.awaiting_pong and self.state == STATE.IDENTIFIED:
# don't let the server's reply to ping reset last_recv unless we're fully
# identified lest we get stuck forever in a partially-connected state
self.ping()
def nick(self, new_nick):
self.conn.send('nick', new_nick)
def join(self, channel):
self.conn.send('JOIN', channel)
def part(self, channel):
self.conn.send('PART', channel)
def say(self, target, message):
self.conn.send('PRIVMSG', target, ':'+message)
def notice(self, target, message):
self.conn.send('NOTICE', target, ':'+message)
def ctcp_reply(self, target, *args):
self.notice(target, '%c%s%c' % (1, ' '.join(args), 1))
def ping(self):
self.conn.send('PING', 'pbot')
self.awaiting_pong = True
#.........这里部分代码省略.........
示例2: Pydis
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import recv [as 别名]
class Pydis(Connection):
def __init__(self, host='127.0.0.1', port=6379, db=0, password=None):
self._conn = Connection(host, port, db, password)
self._conn.connect()
self._pre_cmd = None
self._pre_args = None
def close(self):
if self._conn:
self._conn.close()
def parse_recv(self, recv):
if isinstance(recv, bytes):
logging.debug(recv)
recv_flag, recv_body = chr(recv[0]), recv[1:]
if recv_flag == '-':
if recv_body[:5] == b'MOVED':
skipIpPort = recv_body.decode().strip().split(' ')[-1].split(':')
self._conn.goto_connect(skipIpPort[0], skipIpPort[1])
self._conn._socket.send(self._conn._pre_request);
recv = self._conn.recv()
return self.parse_recv(recv)
else:
logging.error(recv_body)
return recv_body.decode().strip()
elif recv_flag == '+':
recv_list = recv_body.decode().strip().split(CRLF)
if len(recv_list) == 1:
return recv_list[0]
return recv_list[1:]
elif recv_flag == ':':
return int(recv_body)
elif recv_flag == '$':
recv_list = recv_body.decode().strip().split(CRLF)
length_flag = recv_list[0]
if length_flag == -1:
return None
length = len(length_flag) + 5
length += int(length_flag)
while length - self._conn._socket_read_size > 0:
recv += self._conn.recv()
length -= self._conn._socket_read_size
return recv.decode().strip().split(CRLF)[1:]
elif recv_flag == '*':
while not recv.endswith(CRLF.encode()):
recv += self._conn.recv()
recv_body = recv[1:].decode().strip()
recv_list = recv_body.split(CRLF)
while len(recv_list) < 3:
new_recv = self._conn.recv()
while not new_recv.endswith(CRLF.encode()):
new_recv += self._conn.recv()
recv_list.extend(new_recv.decode().strip().split(CRLF))
value_count = recv_list[0]
res = []
i = 1
for x in range(int(value_count)):
if len(recv_list) < i + 1:
new_recv = self._conn.recv()
while not new_recv.endswith(CRLF.encode()):
new_recv += self._conn.recv()
recv_list.extend(new_recv.decode().strip().split(CRLF))
if recv_list[i] != '$-1':
if len(recv_list) < i + 2:
new_recv = self._conn.recv()
while not new_recv.endswith(CRLF.encode()):
new_recv += self._conn.recv()
recv_list.extend(new_recv.decode().strip().split(CRLF))
res.append(recv_list[i + 1])
i += 2
else:
res.append(None)
i += 1
return res
else:
logging.error('')
return recv.decode()
def set_socket_read_size(self, size):
self._conn.set_socket_read_size(size)
def pipeline(self):
return Pipeline(self._conn)
def select_db(self, db):
self._conn.send_command(SELECT, db)
recv = self._conn.recv()
return self.parse_recv(recv)
def ping(self):
self._conn.send_command(PING)
recv = self._conn.recv()
res = self.parse_recv(recv)
return res
def set(self, key, value):
self._conn.send_command(SET, key, value)
recv = self._conn.recv()
res = self.parse_recv(recv)
return res
#.........这里部分代码省略.........
示例3: len
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import recv [as 别名]
if len(sys.argv) < 3:
print >> sys.stderr, 'Usage: python %s HOST PORT' % sys.argv[0]
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
sock = websocket()
sock.connect((host, port))
sock.settimeout(1.0)
conn = Connection(sock)
try:
try:
while True:
msg = TextMessage(raw_input())
print 'send:', msg
conn.send(msg)
try:
print 'recv:', conn.recv()
except socket.timeout:
print 'no response'
except EOFError:
conn.close()
except SocketClosed as e:
if e.initialized:
print 'closed connection'
else:
print 'other side closed connection'
示例4: print
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import recv [as 别名]
try:
bot.getService(service_name).onDestroy(bot)
except AttributeError:
# Don't worry about it since this is optional
pass
sys.exit()
# Register signal handler for ctrl-c to allow bot services to know about their
# impending doom.
signal.signal(signal.SIGINT, SignalHandler)
# Implement the "bot" mainloop
while True:
try:
data = bot.recv()
print(data)
except UnicodeDecodeError:
print("Some unicode!!")
# Stay alive
if data.startswith("PING"):
bot.send("PONG " + data.split()[1])
else:
# TODO: Might be better to put the listeners in their own group apart
# from the "bot".
for m in Message.parse(data):
bot.processListeners(m)