本文整理汇总了Python中socket.bind函数的典型用法代码示例。如果您正苦于以下问题:Python bind函数的具体用法?Python bind怎么用?Python bind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bind函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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, _
开发者ID:qwert42,项目名称:heartbeat-demo-pyzmq,代码行数:32,代码来源:utils.py
示例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]
开发者ID:xymus,项目名称:pycaptain,代码行数:32,代码来源:network.py
示例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")
开发者ID:twosigma,项目名称:beaker-notebook,代码行数:8,代码来源:beakerx_server.py
示例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)
开发者ID:euwen,项目名称:LEHome,代码行数:8,代码来源:MessageHelper.py
示例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
开发者ID:alexmerser,项目名称:server,代码行数:58,代码来源:base.py
示例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'))
开发者ID:langdev,项目名称:nakji,代码行数:9,代码来源:bot.py
示例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
开发者ID:yaobiqing0424,项目名称:pinyin4py,代码行数:9,代码来源:gsd.py
示例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()
开发者ID:ealmansi,项目名称:tdc-tp3,代码行数:10,代码来源:base.py
示例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
开发者ID:08saikiranreddy,项目名称:ipython,代码行数:11,代码来源:entry_point.py
示例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)
开发者ID:dmkusner,项目名称:PythonWorkarea,代码行数:12,代码来源:remote_exec.02.py
示例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())
开发者ID:Endeios,项目名称:synapse,代码行数:14,代码来源:service.py
示例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()
开发者ID:Luavis,项目名称:htt.py,代码行数:16,代码来源:htt.py
示例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 ... "
开发者ID:Cdfghglz,项目名称:indriya,代码行数:17,代码来源:experimot_zmq_client.py
示例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
开发者ID:tavisrudd,项目名称:eventlet,代码行数:17,代码来源:api.py
示例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
开发者ID:supermannba,项目名称:Workspace,代码行数:17,代码来源:androiddevicebt.py
示例16: accept_file
def accept_file():
host= ni.ifaddresses('eth1')[2][0]['addr']
port = 10018
socket.bind((host,port))
socket.listen(5)
conn, addr = socket.accept()
print 'connecting from:',addr
buffer = conn.recv(1024)
global full_path
full_path = buffer.split('\0')[0]
print full_path
global name
temp = full_path.split('/',2)[2]
name = temp.split('.',2)[0]
print name
if True == os.path.isfile(full_path):
print 'file(%s) is already exist'% full_path
del_op= 'rm '+ full_path
os.system(del_op)
dir = full_path.split('.')[0]
if True == os.path.exists(dir):
print "directory already exist %s"% dir
delete_con = 'docker rm -f '+name+ ' >/dev/null 2>&1'
print delete_con
os.system(delete_con)
del_dir = 'rm -fr '+ dir
os.system(del_dir)
conn.send('ready')
#conn, addr = socket.accept()
fname = open(full_path, 'wb')
while True:
strng = conn.recv(4096)
if not strng:
fname.close()
conn.close()
print "recv file success"
break
else:
fname.write(strng)
开发者ID:hixichen,项目名称:CRIU_docker,代码行数:46,代码来源:server.py
示例17: MakeSocket
def MakeSocket(self, context, url = None, type = None, bind = None,
options = None, pre_delay = None, post_delay = None):
"""Create the socket.
Arguments take precendence over their corresponding object attributes.
"""
if type == None:
type = self.type
if url == None:
url = self.url
if bind == None:
bind = self.bind
if options == None:
options = {}
if self.options != None:
if options == None:
options = self.options
else:
options = dict(options.items() + self.options.items())
if pre_delay == None:
pre_delay = self.pre_delay
if post_delay == None:
post_delay = self.post_delay
assert type is not None
socket = context.socket(type)
for k, v in options.items():
socket.setsockopt(k, v)
if pre_delay != None:
time.sleep(pre_delay)
assert url is not None
if bind:
logging.info("Binding %s socket to %s with context %s" % (
SocketTypeToString(type), url, hash(context)))
socket.bind(url)
else:
logging.info("Connecting %s socket to %s with context %s" % (
SocketTypeToString(type), url, hash(context)))
socket.connect(url)
if post_delay != None:
time.sleep(post_delay)
return socket
开发者ID:mandaarp,项目名称:glimpse-project,代码行数:42,代码来源:zmq_cluster.py
示例18: Main
def Main():
socket = socket.socket()
host = '0.0.0.0'
port = 5001
socket.bind((host,port))
socket.listen(10)
c, addr = socket.accept()
while 1:
c.send("StepsS:")
stepsS = c.recv(1024)
c.send("StepsT:")
stepsT = c.recv(1024)
if stepS > 0:
moveforwardS(stepsS)
else:
movebackwardS(-stepsS)
if stepsT > 0:
moveforwardT(stepsT)
else:
movebackwardT(stepsT)
开发者ID:fuhrer196,项目名称:ChessOverIP,代码行数:21,代码来源:serverhack.py
示例19: main
def main():
sim = Simulation(SpeedLimit=0.5, RandomChanges=10) # instantiate the simulation wrapper
# Setup comm sockets
context = zmq.Context()
socket = context.socket(zmq.PUB) # publish to all upstreams services
socket.bind("tcp://127.0.0.1:5550") # localhost only, no encryption
# Main Loop
while True:
# --------------------------------------------------------------------------
# Calculate next round
# --------------------------------------------------------------------------
sim.Solve()
# TODO destabilization code - restore?
# --------------------------------------------------------------------------
# Send state to visualization/freq model
# --------------------------------------------------------------------------
socket.send_json(sim.Output())
开发者ID:besserIO,项目名称:gridmodel,代码行数:21,代码来源:main.py
示例20: run
def run(self):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:%d" % self.port)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
while not self.stopped():
# timeout so we can free the socket and quit the program
# if necessary; in ms
socks = dict(poller.poll(timeout=100))
if socket in socks and socks[socket] == zmq.POLLIN:
print("got dns question")
msg = socket.recv()
if msg in self.database.domains:
domain = self.database.domains[msg]
socket.send("%s %d" % (domain.ip, domain.ttl))
else:
socket.send("0.0.0.0 %d" % default_ttl)
开发者ID:Mondego,项目名称:pyreco,代码行数:21,代码来源:allPythonContent.py
注:本文中的socket.bind函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论