本文整理汇总了Python中socket.socket方法的典型用法代码示例。如果您正苦于以下问题:Python socket.socket方法的具体用法?Python socket.socket怎么用?Python socket.socket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.socket方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ip_latency_test
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def ip_latency_test(ip, port=443):
tag = 'IP_Latency_TEST'
print_with_tag(tag, ['Prepare IP latency test for ip', ip, 'Port', str(port)])
s_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_test.settimeout(10)
s_start = time.time()
try:
s_test.connect((ip, port))
s_test.shutdown(socket.SHUT_RD)
except Exception as e:
print_with_tag(tag, ['Error:', e])
return None
s_stop = time.time()
s_runtime = '%.2f' % (1000 * (s_stop - s_start))
print_with_tag(tag, [ip, 'Latency:', s_runtime])
return float(s_runtime)
示例2: wait_for_port
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def wait_for_port(host, port, timeout=600, print_progress=True):
if print_progress:
sys.stderr.write("Waiting for {}:{}...".format(host, port))
sys.stderr.flush()
start_time = time.time()
while True:
try:
socket.socket().connect((host, port))
if print_progress:
sys.stderr.write(GREEN("OK") + "\n")
return
except Exception:
time.sleep(1)
if print_progress:
sys.stderr.write(".")
sys.stderr.flush()
if time.time() - start_time > timeout:
raise
示例3: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def __init__(self, eventHandler):
threading.Thread.__init__(self)
self.name = 'Server'
self.daemon = True
self._eventHandler = eventHandler
self._client = None
self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._server.bind(('', PORT))
self._server.listen(5)
except socket.error:
event = Event(Events.SCAN_ERROR, msg='Could not start server')
post_event(eventHandler, event)
return
self._cancel = False
self.start()
示例4: run
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def run(self):
while not self._cancel:
if self._client is None:
endpoints = [self._server]
else:
endpoints = [self._server, self._client]
read, _write, error = select.select(endpoints, [], [], 0.5)
for sock in read:
if sock is self._server:
try:
client, _addr = self._server.accept()
if self._client is not None:
self._client.close()
self._client = client
except socket.error:
self._client = None
for sock in error:
if sock is self._client:
self._client = None
sock.close()
示例5: connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def connect(self):
if self.is_server:
log.debug("waiting for client to connect...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', self.port))
s.settimeout(0.1)
start_time = time.time()
s.listen(0)
while True:
try:
conn, _ = s.accept()
self.conn = conn
break
except socket.timeout:
pass
if self.timeout > 0 and time.time() - start_time >= self.timeout:
s.close()
raise RuntimeError("Timeout exceeded (%ds)" % self.timeout)
self.conn.setblocking(True)
else:
log.debug("connecting to server (%s:%d)...", self.ip, self.port)
self.conn = socket.create_connection((self.ip, self.port), self.timeout)
示例6: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def __init__(self, name, intfDict,
asNum, neighbors, routes=[],
quaggaConfFile=None,
zebraConfFile=None,
runDir='/var/run/quagga', *args, **kwargs):
super(BgpRouter, self).__init__(name, intfDict, **kwargs)
self.runDir = runDir
self.routes = routes
if quaggaConfFile is not None:
self.quaggaConfFile = quaggaConfFile
self.zebraConfFile = zebraConfFile
else:
self.quaggaConfFile = '%s/quagga%s.conf' % (runDir, name)
self.zebraConfFile = '%s/zebra%s.conf' % (runDir, name)
self.asNum = asNum
self.neighbors = neighbors
self.generateConfig()
self.socket = '%s/zebra%s.api' % (self.runDir, self.name)
self.quaggaPidFile = '%s/quagga%s.pid' % (self.runDir, self.name)
self.zebraPidFile = '%s/zebra%s.pid' % (self.runDir, self.name)
示例7: config
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def config(self, **kwargs):
super(BgpRouter, self).config(**kwargs)
self.cmd('%s/zebra -d -f %s -z %s -i %s'
% (BgpRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
while True:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
s.connect(self.socket)
#print 'connected - breaking'
s.close()
break
except Exception, e:
#print' ERROR: ' + repr(e)
time.sleep(.1)
#print 'zebra ready'
示例8: create_command_listener
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def create_command_listener (baddr, port):
try:
if port is None:
try:
if os.path.exists(baddr):
os.unlink(baddr)
except OSError:
print 'could not remove old unix socket ' + baddr
return
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
s.bind(baddr)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((baddr, int(port)))
except socket.error , msg:
print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n'
return
示例9: connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def connect (host, why):
# should be either a listener host or a router host (edge-router)
if host not in bgprouters and host not in hosts and host not in participants:
log.error('MM:' + host + ' ERROR: ' + why + ': Unknown host: ' + host)
return None
try:
hostdata = hosts[host]
except:
try:
hostdata = bgprouters[host]
except:
hostdata = participants[host]
#print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)
try:
if hostdata.port is None:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
s.connect(hostdata.host)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostdata.host, int(hostdata.port)))
except Exception, e:
log.error('MM:' + host + ' ERROR: ' + why + ': ' + repr(e))
return None
示例10: router
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def router (args):
if len(args) < 2:
log.error('MM:00 ROUTER: ERROR: usage: router arg arg ...')
return
host = args[0]
if host not in bgprouters:
log.error('MM:' + host + ' ERROR: ' + 'ROUTER' + ' ' + host + ' : must be a BGP router')
return
del args[0]
cmd = ''
for arg in args:
cmd += '"' + arg + '" '
log.info('MM:' + host + ' ROUTER: ' + cmd)
r = generic(host, 'ROUTER', 'router ' + cmd + '\n')
if r is not None:
log.debug('MM:' + host + ' ROUTER: output = \n' + r.strip())
# generic command interface to a tnode - send cmd, capture data
# return None id cannot connect or socket error
# return '' if no data
示例11: genericObjNW
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def genericObjNW (host, label, cmd):
if host not in participants:
log.error('MM:' + host + ' ERROR: ' + label + ': Can only send to a participant: ' + host)
return None
try:
hostdata = hosts[host]
except:
try:
hostdata = bgprouters[host]
except:
hostdata = participants[host]
#print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)
try:
if hostdata.port is None:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
s.connect(hostdata.host)
else:
s = Client((hostdata.host, int(hostdata.port)))
except Exception, e:
log.error('MM:' + host + ' ERROR: ' + label + ': ' + repr(e))
return None
示例12: fileGet
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def fileGet(name):
PORT3 = 50009
ss2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss2.connect((IP, PORT3))
message = 'get ' + name
ss2.send(message.encode())
fileName = '.\\Client_image_cache\\' + name
print('Start downloading image!')
print('Waiting.......')
with open(fileName, 'wb') as f:
while True:
data = ss2.recv(1024)
if data == 'EOF'.encode():
print('Download completed!')
break
f.write(data)
time.sleep(0.1)
ss2.send('quit'.encode())
# 将图片上传到图片服务端的缓存文件夹中
示例13: video_invite
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def video_invite():
global IsOpen, Version, AudioOpen
if Version == 4:
host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
else:
host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
-1]
invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
s.send(invite.encode())
if not IsOpen:
vserver = vachat.Video_Server(10087, Version)
if AudioOpen:
aserver = vachat.Audio_Server(10088, Version)
aserver.start()
vserver.start()
IsOpen = True
示例14: send
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def send(self, channel_type, message, additional_data):
if channel_type == common.CONTROL_CHANNEL_BYTE:
transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
else:
transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)
common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)
# WORKAROUND?!
# Windows: It looks like when the buffer fills up the OS does not do
# congestion control, instead throws and exception/returns with
# WSAEWOULDBLOCK which means that we need to try it again later.
# So we sleep 100ms and hope that the buffer has more space for us.
# If it does then it sends the data, otherwise tries it in an infinite
# loop...
while True:
try:
return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
except socket.error as se:
if se.args[0] == 10035: # WSAEWOULDBLOCK
time.sleep(0.1)
pass
else:
raise
示例15: stop
# 需要导入模块: import socket [as 别名]
# 或者: from socket import socket [as 别名]
def stop(self):
self._stop = True
if self.threads:
for t in self.threads:
t.stop()
# not so nice solution to get rid of the block of listen()
# unfortunately close() does not help on the block
try:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverbind = self.config.get("Global", "serverbind")
if serverbind == "0.0.0.0":
# windows does not like to connect to 0.0.0.0
serverbind = "127.0.0.1"
server_socket.connect((serverbind, int(self.config.get(self.get_module_configname(), "serverport"))))
except:
pass
return