本文整理汇总了Python中socket.listen函数的典型用法代码示例。如果您正苦于以下问题:Python listen函数的具体用法?Python listen怎么用?Python listen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了listen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bind_and_listen_on_posix_socket
def bind_and_listen_on_posix_socket(socket_name, accept_callback):
"""
:param accept_callback: Called with `PosixSocketConnection` when a new
connection is established.
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
assert callable(accept_callback)
# Py2 uses 0027 and Py3 uses 0o027, but both know
# how to create the right value from the string '0027'.
old_umask = os.umask(int('0027', 8))
# Bind socket.
socket_name, socket = _bind_posix_socket(socket_name)
_ = os.umask(old_umask)
# Listen on socket.
socket.listen(0)
def _accept_cb():
connection, client_address = socket.accept()
# Note: We don't have to put this socket in non blocking mode.
# This can cause crashes when sending big packets on OS X.
posix_connection = PosixSocketConnection(connection)
accept_callback(posix_connection)
get_event_loop().add_reader(socket.fileno(), _accept_cb)
logger.info('Listening on %r.' % socket_name)
return socket_name
示例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: __prepare_read
def __prepare_read(self, input_id):
input_format, socket, conn, file_like = self.inputs[input_id]
if not conn:
socket.listen(1)
c = socket.accept()
new_conn, addr = c
conn = new_conn
self.inputs[input_id] = (input_format, socket, conn, conn.makefile())
示例4: 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
示例5: run
def run(socket):
socket.bind((address, port))
socket.listen()
launched_event.set()
try:
socket.accept(timeout=self.DEFAULT_TIMEOUT)
self.end_event.wait()
socket.free()
except Exception, e:
traceback.print_exc(e)
self.network.close()
示例6: 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
示例7: func_name1
def func_name1():
import socket
s = socket.socket(socket.AF_INET,SOCK_STREAM)
#socket.AF_INET-->基于IP的; SOCK_STREAM-->tcp/ip
s.bind(('127.0.0.1',8125))
#输入的是一个元组(ip,端口)-->绑定ip和端口
socket.listen(8)
#n代表允许多少个同时请求,超过的需要等待队列
while True:
connection,address = s.accept() #没有请求的时候会停在这里
buf = connection.recv(1024)
connection.send(buf)
s.close()
示例8: 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
示例9: 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)
示例10: 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)
示例11: createMsg
def createMsg(msg):
return msg + '#'
SERVER_IP = 'localhost'
SERVER_PORT = 5678
BUFFER_SIZE = 1024
TIME_OUT = 10 # 10 seconds
ans = "answer"
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((SERVER_IP, SERVER_PORT))
print ('server started')
while True:
try:
socket.listen(1)
conn, addr = socket.accept()
conn.settimeout(TIME_OUT)
question1 = ''
for i in range (10):
print("connection accepted3")
question1 = str( conn.recv(BUFFER_SIZE) )
print("connection accepted4")
while not '#' in question1:
question1 = str( conn.recv(BUFFER_SIZE) )
print(question1)
conn.send(createMsg(ans))
break
示例12: input
import socket
HOST = ''
PORT = 6030
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(2)
conexion, address = socket.accept()
print ("Cliente: ", address)
while 1:
data = conexion.recv(1024)
if not data:
break
else:
print (data)
#coneccion.send(data)
dataa = input("Escrbe una respuesta: ")
conexion.send(dataa.encode("utf-8"))
conexion.close()
示例13: listenAccept
def listenAccept(self, socket):
socket.listen(1)
sck, address = socket.accept()
self.socketHost = sck
示例14:
modeLabel.setLabel('Navigation')
#print modeLabel.getId()
win.addControl(modeLabel)
#blocking simple server-blocking in order to clean up if connection expires.
host = socket.gethostname()
port = 50000
backlog = 5
size = 1024
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket.bind((host,port))
socket.listen(backlog)
#socket.settimeout(60)
socketFlag = True
try:
connection, address = socket.accept()
except timeout:
print "waiting connection timed out"
socketFlag = False
while socketFlag:
try:
data = connection.recv(1024)
#Do things
#possibly implement this as json handler at some point
print data
示例15: process_data
import entity
def process_data(entity, data):
func_list = data.split(' ')
for func_name in func_list:
if len(func_name) > 0 :
func = getattr(entity, func_name)
if not func:
print 'function %s not found!' % func_name
continue
func()
if __name__ == '__main__':
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('127.0.0.1', 4000))
socket.listen(0)
socket.setblocking(0)
entity = entity.entity()
clients = {}
while True:
conn = None
addr = None
try:
conn, addr = socket.accept()
except:pass
if conn:
print 'find new connection'
clients[addr[0]+str(addr[1])] = conn
for client_id, client in clients.iteritems():
data = ''