本文整理汇总了Python中socket.bind函数的典型用法代码示例。如果您正苦于以下问题:Python bind函数的具体用法?Python bind怎么用?Python bind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bind函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wait_for_ack
def wait_for_ack(ip=local_ip, port=None,
socket_type=zmq.PAIR,
**additional_info):
socket = ctx.socket(socket_type)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
if not ip:
ip = get_local_ip()
if not port:
port = socket.bind_to_random_port('tcp://%s' % ip)
else:
socket.bind('tcp://%s:%s' % (ip, port))
def _(timeout=3 * 1000):
if poller.poll(timeout):
m = socket.recv_json()
socket.close()
assert 'act' in m
assert 'ack' == m['act']
for k, v in additional_info.items():
if k not in m:
return False
if v != m[k]:
return False
return True
return port, _
示例2: __init__
def __init__( self, game, addresses, port, versionString, adminPassword ):
self.game = game
self.versionString = versionString
self.shutdownOrder = False
self.adminPassword = adminPassword
self.rawConnections = []
self.playerCons = []
self.sockets = []
self.updating = {}
self.socketsOpened = []
self.listening = False
### open listener sockets
for address in addresses:
try:
socket = SocketType()
socket.setblocking(0)
socket.bind( ( address, port ) )
socket.listen( 10 )
socket.setblocking( 0 )
print "opened socket on %s:%i" % (address,port)
self.sockets.append( socket )
self.socketsOpened.append( address )
self.listening = True
tSocket = Thread( name="socket on %s:%i"%(address,port), target=self.threadListener, args=(socket,) )
tSocket.start()
except Exception, ex:
print "failed to open socket on %s:"%address, ex[1]
示例3: threaded_function
def threaded_function(self):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind(self.url)
while True:
message = socket.recv()
self.queue.put(message)
socket.send_string("Ok")
示例4: _cmd_worker
def _cmd_worker(self):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind(self.cmd_address)
while True:
cmd = socket.recv_string()
res = self._handle_cmd(cmd)
socket.send_string(res)
示例5: start
def start(self, testing=False):
"""Primary reactor loop.
This handles standard signals as interpreted by Python, such as Ctrl+C.
"""
log.info("Starting up.")
socket = self.socket = self._socket()
socket.bind(self.address)
socket.listen(self.pool)
if self.fork is None:
self.fork = self.processors()
elif self.fork < 1:
self.fork = min(1, self.processors() + self.fork)
# Single-process operation.
if self.fork == 1:
self.serve(testing=testing)
return
# Multi-process operation.
log.info("Pre-forking %d processes from PID %d.", self.fork, os.getpid())
for i in range(self.fork):
if os.fork() == 0:
try:
random.seed(long(hexlify(os.urandom(16)), 16))
except NotImplementedError:
random.seed(int(time.time() * 1000) ^ os.getpid())
self.serve(False)
return
try:
os.waitpid(-1, 0)
except OSError:
pass
except KeyboardInterrupt:
log.info("Recieved Control+C.")
except SystemExit:
log.info("Recieved SystemExit.")
raise
except:
log.exception("Unknown server error.")
raise
self.stop()
return
示例6: zmq_listener
def zmq_listener():
context = zmq.Context()
socket = context.socket(zmq.PULL)
socket.bind(ZMQ_SUB_LISTEN_ADDR)
while True:
msg = socket.recv()
if '\n' in msg or '\r' in msg:
continue
send_line(msg.decode('utf-8'))
示例7: create_socket
def create_socket(socktype, endpoints,flag):
socket = zmq.Socket(zmq.Context.instance(), socktype)
socket.setsockopt(zmq.LINGER, 0)
for endpoint in endpoints:
if flag==1:
socket.bind(endpoint)
else:
socket.connect(endpoint)
return socket
示例8: run
def run(socket):
socket.bind((address, port))
try:
socket.connect((self.DEFAULT_SRC_ADDRESS,
self.DEFAULT_SRC_PORT))
self.end_event.wait()
socket.free()
except Exception, e:
traceback.print_exc(e)
self.network.close()
示例9: bind_port
def bind_port(socket, ip, port):
""" Binds the specified ZMQ socket. If the port is zero, a random port is
chosen. Returns the port that was bound.
"""
connection = 'tcp://%s' % ip
if port <= 0:
port = socket.bind_to_random_port(connection)
else:
connection += ':%i' % port
socket.bind(connection)
return port
示例10: start_listener
def start_listener(port):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:{}".format(port))
while True:
# Wait for next request from client
message = socket.recv()
socket.send("")
if message == "Done!":
break
print ("Received message: %s" % message)
示例11: start
def start(self):
socket = self.ctx.socket(zmq.REP)
service_address = self.my_conf.get("Service","service_default_bind_address")
log.debug("Serving at %s"%service_address)
socket.bind(service_address)
log.debug("Start serving")
while True:
message = socket.recv()
log.debug("Message received: %s"%message)
command = self.my_conf.get("Service","command")
command_list = command.split(" ")
log.debug("Execution of: %s"%command_list)
cmd = subprocess.Popen(command_list,stdout=subprocess.PIPE)
socket.send(b"|%s|"%cmd.stdout.read())
示例12: main
def main():
print("[HTT] Start server")
socket = HTTPSocket()
print("[HTT] bind 8080")
socket.bind(8080)
# get connection
conn, addr = socket.accept()
while conn is not None:
thread = HTTPMainThread(conn, 1024, addr[0], addr[1])
thread.run()
conn, addr = socket.accept()
示例13: localization_server
def localization_server(ip,port):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind(("tcp://*:%d" % port))
dummy = { 'pos' : {'x':'100','y':'100','z':'100'}, 'orient': {'w':'1','x':'0','y':'0','z':'0'}};
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: %s" % message)
# Do some 'work'
time.sleep(0.050)
# Send reply back to client
socket.send(json.dumps(dummy))
print "quitting ... "
示例14: ssl_listener
def ssl_listener(address, certificate, private_key):
"""Listen on the given (ip, port) *address* with a TCP socket that
can do SSL. Primarily useful for unit tests, don't use in production.
*certificate* and *private_key* should be the filenames of the appropriate
certificate and private key files to use with the SSL socket.
Returns a socket object on which one should call ``accept()`` to
accept a connection on the newly bound socket.
"""
from eventlet import util
import socket
socket = util.wrap_ssl(socket.socket(), certificate, private_key, True)
socket.bind(address)
socket.listen(50)
return socket
示例15: serverlisten
def serverlisten(self,socket,port,time):
host=''
try:
socket.bind((host,port))
except:
print('bind failed, error code'+str(msg[0])+'Message: '+msg[1])
sys.exit()
socket.listen(time)
while True:
conn,addr=socket.accept()
print('conneted with '+addr[0]+':'+str(addr[1]))
data=conn.recv(1024)
result1=data.decode("utf-8")
conn.close()
socket.close()
break
return result1