本文整理汇总了Python中socket.SOCK_STREAM属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SOCK_STREAM属性的具体用法?Python socket.SOCK_STREAM怎么用?Python socket.SOCK_STREAM使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类socket
的用法示例。
在下文中一共展示了socket.SOCK_STREAM属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ip_latency_test
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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()
示例3: connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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)
示例4: config
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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'
示例5: create_command_listener
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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
示例6: connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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
示例7: genericObjNW
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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
示例8: fileGet
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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())
# 将图片上传到图片服务端的缓存文件夹中
示例9: stop
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [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
示例10: check
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def check(self):
try:
common.internal_print("Checking module on server: {0}".format(self.get_module_name()))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(3)
server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
client_fake_thread.do_check()
client_fake_thread.communication(True)
self.cleanup(server_socket)
except socket.timeout:
common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
self.cleanup(server_socket)
except socket.error as exception:
if exception.args[0] == 111:
common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
else:
common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
self.cleanup(server_socket)
return
示例11: mac_set_ip_address
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def mac_set_ip_address(self, dev, ip, serverip, netmask):
ifr = struct.pack('<16sBBHIIIBBHIIIBBHIII',
self.iface_name,
16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, ip))[0], 0, 0,
16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, serverip))[0], 0, 0,
16, 0, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, "255.255.255.255"))[0], 0, 0)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fcntl.ioctl(sock, self.IOCTL_MACOSX_SIOCAIFADDR, ifr)
except Exception as e:
common.internal_print("Something went wrong with setting up the interface.", -1)
print(e)
sys.exit(-1)
# adding new route for forwarding packets properly.
integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))
ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = ps.communicate()
if stderr:
if not "File exists" in stderr:
common.internal_print("Error: adding client route: {0}".format(stderr), -1)
sys.exit(-1)
return
示例12: freebsd_tun_alloc
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def freebsd_tun_alloc(self, dev, flags):
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ifr = struct.pack('<16si', 'tun', 0)
self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
self.iface_name = self.iface_name.rstrip("\x00")
buff = array.array('c', dev+"\x00")
caddr_t, _ = buff.buffer_info()
ifr = struct.pack('16sP', self.iface_name, caddr_t);
fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
self.iface_name = dev
except IOError as e:
print e
common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
sys.exit(-1)
return tun
示例13: acceptThread
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def acceptThread(parameters):
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(parameters['listenPort'])))
acceptor.listen(5)
cur_thread = threading.current_thread()
logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')
while True:
(clientSock, clientAddr) = acceptor.accept()
print "==== Output Request ====="
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
logger.info(msg)
thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
thread3.daemon = True
thread3.start()
acceptor.close()
return
示例14: acceptThread
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def acceptThread():
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(uploadPort)))
acceptor.listen(5)
cur_thread=threading.current_thread()
while True:
(clientSock,clientAddr)=acceptor.accept()
print "====Output Request:"
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
print msg
thread3=threading.Thread(target=sendFile(clientSock))
thread3.daemon=True
thread3.start()
#thread3.join()
acceptor.close()
return
示例15: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOCK_STREAM [as 别名]
def __init__(self, addr: Union[str, tuple, socket.socket]):
"""
Args:
addr: can be /var/run/usbmuxd or (localhost, 27015)
"""
self._sock = None
if isinstance(addr, socket.socket):
self._sock = addr
return
if isinstance(addr, str):
if not os.path.exists(addr):
raise MuxError("socket unix:{} unable to connect".format(addr))
family = socket.AF_UNIX
else:
family = socket.AF_INET
self._sock = socket.socket(family, socket.SOCK_STREAM)
self._sock.connect(addr)