本文整理汇总了Python中connection.Connection方法的典型用法代码示例。如果您正苦于以下问题:Python connection.Connection方法的具体用法?Python connection.Connection怎么用?Python connection.Connection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection
的用法示例。
在下文中一共展示了connection.Connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def run(self):
while True:
if shared.shutting_down:
logging.debug('Shutting down Listener')
break
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
if len(shared.connections) > shared.connection_limit:
conn.close()
else:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
示例2: startBattle
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def startBattle(self, spot, fleet, formation):
try:
data = self.conn.get('/pve/dealto/%d/%d/%d/' % (spot, fleet.id, formation), param='',
headers=self.conn.getHeader,
server=self.conn.getHeader.get('Host'))
if data == -1:
self.Log.i("Connection Error!")
return -1
if 'warReport' in data:
selfHp = data['warReport']['hpBeforeNightWarSelf']
enemyHp = data['warReport']['hpBeforeNightWarEnemy']
else:
selfHp = 0
enemyHp = 0
lastSpot = (int(data['pveLevelEnd']) == 1)
return selfHp, enemyHp, lastSpot
except:
return -1
示例3: __init__
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def __init__(self, syncObj, nodeAddr):
self.__syncObj = weakref.ref(syncObj)
self.__nodeAddr = nodeAddr
self.__ip = syncObj._getResolver().resolve(nodeAddr.split(':')[0])
self.__port = int(nodeAddr.split(':')[1])
self.__poller = syncObj._getPoller()
self.__conn = Connection(socket=None, timeout=syncObj._getConf().connectionTimeout)
self.__shouldConnect = syncObj._getSelfNodeAddr() > nodeAddr
self.__lastConnectAttemptTime = 0
self.__lastPingTime = 0
self.__status = NODE_STATUS.DISCONNECTED
示例4: __onNewConnection
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def __onNewConnection(self, localDescr, event):
if event & POLL_EVENT_TYPE.READ:
try:
sock, addr = self.__socket.accept()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.__conf.sendBufferSize)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.__conf.recvBufferSize)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(0)
conn = Connection(socket=sock, timeout=self.__conf.connectionTimeout)
descr = conn.fileno()
self.__unknownConnections[descr] = conn
self.__poller.subscribe(descr,
self.__processUnknownConnections,
POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.ERROR)
except socket.error as e:
if e.errno != socket.errno.EAGAIN:
self.__isInitialized = False
LOG_WARNING('Error in main socket:' + str(e))
if event & POLL_EVENT_TYPE.ERROR:
self.__isInitialized = False
LOG_WARNING('Error in main socket')
示例5: clean_connections
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def clean_connections():
hosts = set()
outgoing_connections = 0
for c in shared.connections.copy():
if not c.is_alive() or c.status == 'disconnected':
with shared.connections_lock:
shared.connections.remove(c)
else:
hosts.add(c.host)
if not c.server:
outgoing_connections += 1
to_connect = set()
if shared.trusted_peer:
to_connect.add(shared.trusted_peer)
if outgoing_connections < shared.outgoing_connections and shared.send_outgoing_connections and not shared.trusted_peer:
if len(shared.unchecked_node_pool) > 16:
to_connect.update(random.sample(shared.unchecked_node_pool, 16))
else:
to_connect.update(shared.unchecked_node_pool)
shared.unchecked_node_pool.difference_update(to_connect)
if len(shared.node_pool) > 8:
to_connect.update(random.sample(shared.node_pool, 8))
else:
to_connect.update(shared.node_pool)
for addr in to_connect:
if addr[0] in hosts:
continue
c = Connection(addr[0], addr[1])
c.start()
hosts.add(c.host)
with shared.connections_lock:
shared.connections.add(c)
shared.hosts = hosts
示例6: create
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def create(address = "localhost", port = 4711, name = None):
return Minecraft(Connection(address, port), name)
示例7: spawn
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def spawn(self,name,function,arguments=()): # Takes a name, a function and a tuple/list/dict object as arguments, and starts it off in a new thread, returning a reference to the Thread object.
newthread = threading.Thread(name=name, target=function, args=(arguments if type(arguments) in (tuple,list) else ()), kwargs=(arguments if type(arguments) is dict else {}) )
newthread.start(); return newthread
################################################## Connection Initialization/Termination ##################################################
示例8: step
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def step(self,func,args=None): # Can be used to define a function that will be called periodically.
if self.active(): self.debug("Cannot set step function while the connection is active.")
else:
self._step["function"] = func
self._step["args"] = args
self.debug("Step function set successfully.")
return self
################################################## Connection Management ##################################################
示例9: connect
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def connect(self,hubcount): # Connects to the hub.
self.debug("Attempting to connect to Hub ...")
if re.match("^[0-9]+/[0-9]+/[0-9]+$",hubcount) is not None:
self._config["hubcount"] = hubcount
else:
self.debug("Invalid Hub Count.")
return self
if not self._config["ready"]: return self
self._socket = Connection({ "name":"DC Hub", "host":self._config["host"], "port":self._config["port"], "type":"tcp", "role":"client", "handler":self.server_handler, "args":{"buffer":""}, "debug":self._debug })
self.debug("Connected to Hub.")
self._step["active"] = True
self._step["thread"] = self.spawn("Step Function",self.step_actual)
self._download["active"] = True
self._download["thread"] = self.spawn("Download Manager",self.download_manager)
return self
示例10: connect_remote
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def connect_remote(self,nick,rev=True,failure=None): # Sets up a connection with nick
if type(nick) is list:
if len(nick)==0: return self
else: nick=nick[0]
if self._config["mode"]: # Nothing can be done if both are passive
port = random.randint(1000,2**16-1) # Randomly select +ve integer for a part number in the given range
d = { "nick":nick } # This is the prototype for the transfer object, created so that the connection object it will contain will have a reference to it.
self.debug("Sending connection request to "+nick+" ...")
while True: # Keeping trying to bind to different port numbers
try:
d["socket"] = Connection({"name":nick,"host":self._config["localhost"],"port":port,"role":"server","type":"tcp","handler":self.transfer_handler,"args":{"role":"server","transfer":d,"failure":failure,"nick":nick},"debug":self._debug})
break # Terminate loop only after binding to a specific port. Those Connections objects that could not bind have lost their
except ConnectionError: port = random.randint(0,2**16-1) # If this particular port is occupied,try another one randomly
self._transfer.append(d)
for retry in range(self._config["retry"]):
self._socket.send("$ConnectToMe "+nick+" "+self._config["localhost"]+":"+str(port)+"|")
time.sleep(self._config["wait"])
if d["socket"].clients(): return self # Connection Successful
self.debug("No response from "+nick+" after waiting for "+str(self._config["wait"])+" seconds.")
self.debug("Connection to "+nick+" failed - timeout.")
d["socket"].close() # Terminate the server
if failure!=None: failure()
return self
elif rev:
self._socket.send("$RevConnectToMe "+self._config["nick"]+" "+nick+"|")
return self
示例11: search
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def search(self,pattern,result,options={}): # Used to search for a pattern in other users' filelists; result is a function here
if len(pattern)==0: return # Empty searches not allowed.
ss = ["F","F","0","1",self.escape(pattern).replace(" ","$")] # isSizeRestricted, isMaxSize, size, fileType, searchTerm
mode = "manual" # Default mode; "auto" is used when looking for sources for downloads, and has a much smaller wait time.
if type(options) is dict:
for key in options:
if key=="limit": # Size Limit
ss[0]="T" # There is a limit of the size of the file, default being Lower Limit
if options[key]=="max": ss[1]="T" # Upper Limit on Size
if key=="size": ss[2]=str(options[key]) # Actual value of Size Limit
if key=="type" and options[key] in self._filetype: ss[3]=str(self._filetype[options[key]]) # File Type
if key=="mode" and options[key] in ("manual","auto"): mode = options[key] # Search Mode
if "display" not in options: options["display"] = None # Assuming the results are not to be sent to a stream.
ss = "?".join(ss) # Combining all parameters into a search pattern
self._search[ss] = { "mode":mode, "result":result } # Creating a search pseudo object, so that we can keep track of associated information
if self._config["mode"]: # Active Mode
port = random.randint(0,2**16-1) # Choose a random
while True: # Keep trying till a free port is found
try: # Connection constructor might raise an exception
c = Connection({"name":ss,"host":self._config["localhost"],"port":port,"role":"server","type":"udp","handler":self.search_result_process,"args":{"ss":ss,"buffer":""},"debug":self._debug}) # Create a UDP server to listen for Search Results
break # Stop only when the server has been setup
except ConnectionError: port = random.randint(0,2**16-1) # Try another random port
self._search[ss]["socket"] = c # Save the connection into the search object
self._socket.send("$Search %s:%d %s|" % (self._config["localhost"],port,ss)) # Send a search command to the hub that will be echoed to all other clients
self.spawn("SearchTimeout:"+ss,lambda:( time.sleep(self._config[ "searchtime_"+mode ]), c.close() )) # Stop listening for search results after specific amount of time
else: # Passive Mode
self._socket.send("$Search Hub:%s %s|" % (self._config["nick"],ss)) # Send a search command to the hub to be echoed to all peers.
self._search[ss]["socket"] = None # Given passive connections, a limited number of results will be sent back via the hub only, so no dedicated connection is required.
return self
示例12: cli
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def cli(self): # Provide a Command Line Interface for testing purposes before the GUI can be built
"Provides a Command Line Interface for the Direct Connect Client."
print "Command Line Interface"
while True:
try:
x = raw_input()
if x=="!configure":
print "Enter the Client Name : ",; name = raw_input()
print "Enter the Hub Address : ",; host = raw_input()
print "Enter the Nickname you wish to use : ",; nick = raw_input()
print "Enter the Password you wish to use : ",; _pass = raw_input()
self._configure({"name":name, "host":host, "nick":nick, "pass":_pass});
if x=="!connect": self.connect()
if x=="!disconnect": self.disconnect()
if x=="!status": print "Connection Status : "+("mode" if self.active() else "Inactive")
if x=="!nicklist":
for nick in self._config["nicklist"]: print nick, self._config["nicklist"][nick]
if x=="!exit":
self.disconnect()
break
if len(x)>0 and x[0]=="?": self.search(x[1:],{"display":sys.stdout})
if len(x)>0 and x[0]==":": self.mc_send(x[1:])
if len(x)>0 and x[0]=="@": self.pm_send(x[1:].split()[0]," ".join(x.split()[1:]) )
if len(x)>0 and x[0]=="~": exec (x[1:])
if len(x)>0 and x[0]=="$": self._socket.send(x[1:])
if len(x)>0 and x[0]=="^": self.download_tth("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
if len(x)>0 and x[0]=="&": print [item["part"] for item in self._queue]
if len(x)>0 and x[0]=="*":
for t in sorted([t.name for t in threading.enumerate()]): print "THREAD :: "+t
except KeyboardInterrupt: break
except Exception as e: print e
return self
示例13: __init__
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def __init__(self, ip, port, user, password, cipher):
self.node_connection = Connection(ip, port, '', user, password, cipher)
self.mysql_user = user
self.mysql_password = password
示例14: restart
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def restart(self):
self.conn = Connection()
self.conn.get('/index/getInitConfigs/')
loginData = self.conn.get('/index/passportLogin/%s/%s/' % (self.username, self.password))
self.conn.setServer(self.server)
self.conn.get('//index/login/' + loginData['userId'])
self.conn.get('/api/initGame/')
Log.i('Game restarted')
示例15: startStage
# 需要导入模块: import connection [as 别名]
# 或者: from connection import Connection [as 别名]
def startStage(self, stageId, fleet):
try:
data = self.conn.post('/pve/cha11enge/%d/%d/0/' % (stageId, fleet.id), param='pve_level=1&pid=' + str(random.randrange(530000, 580000)),
headers=self.conn.getHeader,
server=self.conn.getHeader.get('Host'))
if data == -1:
self.Log.i("Connection Error!")
return -1
return data[0]
except:
return -1