本文整理汇总了Python中socket.listen函数的典型用法代码示例。如果您正苦于以下问题:Python listen函数的具体用法?Python listen怎么用?Python listen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了listen函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:jonathanslenders,项目名称:pymux,代码行数:33,代码来源:posix.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: __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())
开发者ID:pawellewandowski,项目名称:TIRT,代码行数:8,代码来源:sync.py
示例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
开发者ID:alexmerser,项目名称:server,代码行数:58,代码来源:base.py
示例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()
开发者ID:ealmansi,项目名称:tdc-tp3,代码行数:11,代码来源:base.py
示例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
开发者ID:tavisrudd,项目名称:eventlet,代码行数:17,代码来源:api.py
示例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()
开发者ID:zhoufelix0558,项目名称:python----,代码行数:17,代码来源:socket&http.py
示例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
开发者ID:supermannba,项目名称:Workspace,代码行数:17,代码来源:androiddevicebt.py
示例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)
开发者ID:hixichen,项目名称:CRIU_docker,代码行数:46,代码来源:server.py
示例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)
开发者ID:fuhrer196,项目名称:ChessOverIP,代码行数:21,代码来源:serverhack.py
示例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
开发者ID:amobdi,项目名称:faseeh,代码行数:31,代码来源:server.py
示例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()
开发者ID:J053Fabi0,项目名称:Sockets,代码行数:22,代码来源:server.py
示例13: listenAccept
def listenAccept(self, socket):
socket.listen(1)
sck, address = socket.accept()
self.socketHost = sck
开发者ID:brandonPurvis,项目名称:InterConnect,代码行数:4,代码来源:iccUnittesting.py
示例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
开发者ID:nkiermaier,项目名称:xmbc_leap,代码行数:31,代码来源:main.py
示例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 = ''
开发者ID:rabbit1989,项目名称:rabbit_server,代码行数:31,代码来源:server.py
示例16: Server
#!/usr/bin/python
#Python version is 2.7.9
#Author: Martin Schmidt aka qw2100m
import socket
import time
import select
HOST = ""
PORT = 2269
socket.listen(max_players)
class Server():
def __init__(self, host, port):
self.HOST = host
self.PORT = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((HOST, PORT))
def wait_for_connections(self):
"""Just wait for everybody to connect."""
self.max_players = input("Max number of players:")
# Sockets from which we expect to read
inputs = [ server ]
开发者ID:qw2100m,项目名称:PySail,代码行数:26,代码来源:WindyServer.py
示例17:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
socket.listen()
开发者ID:rishigb,项目名称:kinectHacks,代码行数:11,代码来源:createServerPythonUdp.py
示例18: createServer
def createServer(socket):
print 'Starting server on %s:%s' % server_addr
socket.bind(server_addr)
socket.listen(5)
开发者ID:LoganRickert,项目名称:NASA-Robot-Arduino-RPI,代码行数:5,代码来源:control_socket_xbox_controller.py
示例19: path_leaf
import socket
#import sys
import os
import ntpath
#from _thread import start_new_thread
HOST = '' # server name goes in here
PORT = 4444
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(10)
logged_user = ''
# def clientthread(conn):
logged_user = ''
while True:
conn, addr = socket.accept()
print ('New client connected ..')
#start_new_thread(clientthread, (conn,))
reqCommand = conn.recv(1024).decode('utf-8')
print ('Client> %s.' %reqCommand)
if (reqCommand == 'out'):
print('User %s logged out.' %logged_user)
logged_user = ''
#break
开发者ID:TopHatCroat,项目名称:Oblak,代码行数:30,代码来源:server.py
示例20: int
lproto = sys.argv[1]
lport = int(sys.argv[2])
outfile = sys.argv[3]
print "Firing up " + lproto + " listener on ", lport
print "Writing to file", outfile
print "-------------------------------------"
if lproto == "tcp":
proto = socket.SOCK_STREAM
elif lproto == "udp":
proto = socket.SOCK_DGRAM
else:
sys.exit("Wrong protocol.")
socket = socket.socket(socket.AF_INET, proto)
socket.bind(("", lport))
socket.listen(5)
while 1:
connection, addr = socket.accept()
print "New connection from: ", addr
data = connection.recv(1024)
connection.close()
print "Data received: ", data
outputfile = open(outfile, "a")
outputfile.write(data)
socket.close()
outputfile.close()
开发者ID:PeterMosmans,项目名称:Scripts,代码行数:30,代码来源:listener.py
注:本文中的socket.listen函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论