本文整理汇总了Python中socket.close函数的典型用法代码示例。如果您正苦于以下问题:Python close函数的具体用法?Python close怎么用?Python close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了close函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: voyagerSearchResultsService
def voyagerSearchResultsService(self,searchType=None,resultPointer="0",maxResultsPerPage="10",sortBy="TITLE",profileCode=None):
"""
Voyagers SearchResultsService
@param searchType: FIND,BROWSE,etc
@param resultPointer: Current position in result set.
@param maxResultsPerPage: Number of results returned
@param sortBy: Field to sort on.
@param profileCode: Ignore, used only one RELBIBS
@return: xml
"""
self.xmldoc = None
if searchType != None:
query = ("searchType=" + searchType +
"&resultPointer=" + resultPointer +
"&maxResultsPerPage=" + maxResultsPerPage +
"&sortBy=" + sortBy)
try:
print str(self._getVoyagerUrl()) + "/SearchResultsService?" + query
socket = self.session.open(str(self._getVoyagerUrl()) + "/SearchResultsService?" + query,timeout=self.DEFAULT_TIMEOUT_SECONDS)
self.xmldoc = minidom.parse(socket).documentElement
socket.close()
except Exception as e:
logger.warning(e)
#print self.xmldoc.toprettyxml(encoding='utf-8')
return self.xmldoc
开发者ID:uwosh,项目名称:uwosh.libraryguides,代码行数:25,代码来源:VoyagerHandler.py
示例2: stop
def stop(self):
"""
Stops the backend process.
"""
if self._process is None:
return
if self._shared:
BackendManager.SHARE_COUNT -= 1
if BackendManager.SHARE_COUNT:
return
_logger().debug('stopping backend process')
# close all sockets
for socket in self._sockets:
socket._callback = None
socket.close()
self._sockets[:] = []
# prevent crash logs from being written if we are busy killing
# the process
self._process._prevent_logs = True
while self._process.state() != self._process.NotRunning:
self._process.waitForFinished(1)
if sys.platform == 'win32':
# Console applications on Windows that do not run an event
# loop, or whose event loop does not handle the WM_CLOSE
# message, can only be terminated by calling kill().
self._process.kill()
else:
self._process.terminate()
self._process._prevent_logs = False
_logger().info('backend process terminated')
开发者ID:sopak,项目名称:cadquery-freecad-module,代码行数:31,代码来源:backend.py
示例3: server
def server(self,parent,answer=False,pre_return=False):
while True:
print "server started"
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('',parent.port))
sock.listen(5)
try:
while True:
newSocket, address = sock.accept()
debug_print("ip address: "+str(address),1)
while True:
try:
print "ready to receive:"
receivedData=newSocket.recv(4*8192)#maybe we should increase the max receive data
except:
print "socket error"
if not receivedData:
print "no data"
break
if receivedData=="alive?":
print "alive"
newSocket.sendall("alive!"+";\r\n") #added TK
break
if pre_return:
try:
newSocket.sendall("RECEIVED!"+";\r\n") #added TK
except:
debug_print("error while sending return string",1)
debug_print("received data: " + str(receivedData),1)
start_time=time.time()
parent.server_create(receivedData)
stop_time=time.time()
used_time=round((stop_time-start_time)*1000)
parent.time_str="OK, execution_time, " +str(used_time)+";\n"
if (parent.error_string==""):
if answer:
print "trying to send"
string=parent.get_return_string()
try:
newSocket.sendall(string+"\r\n")
except:
debug_print("error while returning value",1)
debug_print("returned value"+str(parent.get_return_string())+"\r\n",1)
else:
print"trying to send error"
if answer:
newSocket.sendall(parent.error_string+"\r\n")
parent.error_string=""
print "sended error"
print "finish connected"
newSocket.close()
finally:
print "disconnected"
try:
socket.close()
except AttributeError:
debug_print("server crashed - restarting",1)
开发者ID:imrehg,项目名称:pulse-programmer,代码行数:60,代码来源:server.py
示例4: get_replay
def get_replay(name, query, config, context=None):
endpoint = config.get('replay_endpoints', {}).get(name, None)
if not endpoint:
raise IOError("No appropriate replay endpoint "
"found for {0}".format(name))
if not context:
context = zmq.Context(config['io_threads'])
# A replay endpoint isn't PUB/SUB but REQ/REP, as it allows
# for bidirectional communication
socket = context.socket(zmq.REQ)
try:
socket.connect(endpoint)
except zmq.ZMQError as e:
raise IOError("Error when connecting to the "
"replay endpoint: '{0}'".format(str(e)))
# REQ/REP dance
socket.send(fedmsg.encoding.dumps(query))
msgs = socket.recv_multipart()
socket.close()
for m in msgs:
try:
yield fedmsg.encoding.loads(m)
except ValueError:
# We assume that if it isn't JSON then it's an error message
raise ValueError(m)
开发者ID:axilleas,项目名称:fedmsg,代码行数:29,代码来源:__init__.py
示例5: test_preexisting_token_sans_splunk
def test_preexisting_token_sans_splunk(self):
token = self.context.token
if token.startswith('Splunk '):
token = token.split(' ', 1)[1]
self.assertFalse(token.startswith('Splunk '))
else:
self.fail('Token did not start with "Splunk ".')
opts = self.opts.kwargs.copy()
opts["token"] = token
opts["username"] = "boris the mad baboon"
opts["password"] = "nothing real"
newContext = binding.Context(**opts)
response = newContext.get("/services")
self.assertEqual(response.status, 200)
socket = newContext.connect()
socket.write("POST %s HTTP/1.1\r\n" %\
self.context._abspath("some/path/to/post/to"))
socket.write("Host: %s:%s\r\n" %\
(self.context.host, self.context.port))
socket.write("Accept-Encoding: identity\r\n")
socket.write("Authorization: %s\r\n" %\
self.context.token)
socket.write("X-Splunk-Input-Mode: Streaming\r\n")
socket.write("\r\n")
socket.close()
开发者ID:justinlmeyer,项目名称:splunk-sdk-python,代码行数:27,代码来源:test_binding.py
示例6: server
def server(pid, ep):
"""
Worker for listening socket for communication with web server.
Parameters
----------
pid: int
Process id. Used to send SIGINT.
ep: mp.Pipe endpoint.
Used to communicate with model processor.
"""
context = zmq.Context()
socket = context.socket(zmq.REP)
port = socket.bind_to_random_port("tcp://0.0.0.0")
ep.send(port)
def sig_handler(signum, frame):
socket.close()
return
signal.signal(signal.SIGTERM, sig_handler)
while True:
message = socket.recv()
if message == "KILL":
socket.send("OK")
socket.close()
ep.send(None)
p = psutil.Process(pid)
p.send_signal(signal.SIGINT)
return
开发者ID:ecastrow,项目名称:pl2mind,代码行数:31,代码来源:__init__.py
示例7: handle_tcp
def handle_tcp(socket, dstport):
handler = tcp_handlers.get(dstport, handle_tcp_default)
try:
handler(socket, dstport)
except Exception as err:
print(traceback.format_exc())
socket.close()
开发者ID:fabio-d,项目名称:honeypot,代码行数:7,代码来源:main.py
示例8: handle
def handle(socket, address):
unparsed_data = socket.recv(1024)
parsed_http_response = HTTPRequestParser(unparsed_data)
# Message formatting and message sending are separated for ease of testing.
if parsed_http_response.error_code is not None:
server_response = return_error(parsed_http_response)
socket.send(server_response)
elif parsed_http_response.request_version != "HTTP/1.1":
server_response = return_unsupported_version(parsed_http_response)
socket.send(server_response)
elif parsed_http_response.command != "GET":
server_response = return_method_not_allowed(parsed_http_response)
socket.send(server_response)
elif parsed_http_response.error_code is None:
# note to self: feed the returns from
# return_requested_file_or_directory()
# into a response crafter which does header creation.
server_response = \
return_ok_http_file_or_directory_response(parsed_http_response)
socket.send(server_response)
socket.close()
开发者ID:BFriedland,项目名称:network_tools,代码行数:28,代码来源:http_server_helper.py
示例9: send_data_to
def send_data_to(self, sock, message):
try:
sock.send(message)
except:
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
self.CONNECTION_LIST.remove(sock)
开发者ID:alexwhb,项目名称:simple-python-chat-server,代码行数:7,代码来源:server.py
示例10: cleanup
def cleanup (arg1 = None, arg2 = None):
global clients
log("Cleaning up")
running = False
for socket in clients:
try:
socket.shutdown(socket.SHUT_RDWR)
except Exception as e:
pass
socket.close()
if unix_socket:
unix_socket.shutdown(socket.SHUT_RDWR)
unix_socket.close()
if tcp_socket:
tcp_socket.shutdown(socket.SHUT_RDWR)
tcp_socket.close()
if serial_con:
serial_con.close()
try:
os.remove('/tmp/lights')
except OSError, e: pass
try:
os.remove(config['pidfile'])
except OSError, e: pass
开发者ID:blubber,项目名称:kastje,代码行数:30,代码来源:server.py
示例11: serve
def serve(self):
self._running = True
socket = evtapi.tcp_listener((self.host,self.port))
while self._running:
client, _ = socket.accept()
Dispatcher(client,self.mapper).dispatch()
socket.close()
开发者ID:mbreese,项目名称:proxylet,代码行数:7,代码来源:__init__.py
示例12: listen_on_socket
def listen_on_socket(socket, *args):
if socket is None:
return
command = ""
file = socket.makefile('rwb')
while True:
try:
data = file.read(1)
if data == b'':
sleep(0.001)
continue
else:
data = data.decode('ascii')
if data == AtHomeProtocol['end_of_communication']:
print('Communication ended', file=sys.stderr)
return
if data != AtHomeProtocol['end_of_command']:
command += data
else:
command = ""
continue
if command.endswith(AtHomeProtocol['end_of_line']):
command = command[0:-2]
if command in AtHomeCommands:
AtHomeCommands[command](file)
else:
command = ""
raise NameError('[Unknown Command] %s' % command)
command = ""
except EOFError:
file.close()
socket.close()
return
except Exception as e:
print('[Exception] %s' % e, file=sys.stderr)
开发者ID:AtHomeEIP,项目名称:middleware,代码行数:35,代码来源:SocketMiddleware.py
示例13: file_send
def file_send(self, socket):
print('Thread for client ' + str(socket) + ' started! Waiting for input...')
# headers = conn.recv(1024)
# print('headers: %s' % headers)
# data = self.msg_get(socket)
# print(data)
#
# # socket.send('tarantino.jpg'.encode('utf-8'))
# self.msg_send(socket, 'tarantino.jpg')
# print('send filename')
# # socket.close()
# socket = self.connect()
with open(self.default_server_file, 'rb') as file:
print('File open')
l = file.read(1024)
while l:
socket.send(l)
# print('sending data...')
l = file.read(1024)
print('sending data: END...')
socket.close()
开发者ID:suhodolik,项目名称:client-serv,代码行数:25,代码来源:server.py
示例14: socket_timeout
def socket_timeout(self, key, aliases):
'''
check whether the connection timed out
This happens when a socket is still in self.master.pending_connections
after a certain amount of time
'''
then=time.time() + TIMEOUT
while time.time() < then:
with self.master.pending_connections_lock:
if not key in self.master.pending_connections:
return
time.sleep(CHECK_RATE)
with self.master.pending_connections_lock:
if not key in self.master.pending_connections:
return
(from_aliases, socket) = self.master.pending_connections.pop(key)
socket.close()
for bot_index in from_aliases:
with self.master.bots[bot_index].num_clients_lock:
self.master.bots[bot_index].num_clients -= 1
with self.master.peer_resources_lock:
if key[1] in self.master.peer_resources:
self.send_disconnect_error(key, from_aliases, self.master.peer_resources[key[1]])
else:
self.send_disconnect_error(key, from_aliases, key[1], message=True)
开发者ID:aeftimia,项目名称:hexchat,代码行数:31,代码来源:server_socket.py
示例15: send_data
def send_data(socket):
while True:
data = input()
socket.send(data.encode('utf-8'))
if(data == 'exit'):
socket.close()
break
开发者ID:dh-Chen,项目名称:chat,代码行数:7,代码来源:ient3.py
示例16: _socketRequest
def _socketRequest(self, scheme, host, port, payload):
socket = self._getSocketForScheme(scheme)
socket.connect((host, port))
socket.sendall(payload)
data = socket.recv(1024)
socket.close()
return data
开发者ID:buglloc,项目名称:pocs,代码行数:7,代码来源:file_uploader.py
示例17: upload
def upload(self):
self.getDuration()
# Take screenshots at even increments between 20% and 80% of the duration
stops = range(20,81,60/(self.shots-1))
try:
count=0
imgs = []
for stop in stops:
imgs.append(tempdir()+"screen%d.png" % count)
subprocess.Popen([r"ffmpeg","-ss",str((self.duration * stop)/100), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", imgs[-1] ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait()
count+=1
except OSError:
sys.stderr.write("Error: Ffmpeg not installed, refer to http://www.ffmpeg.org/download.html for installation")
exit(1)
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
try:
for img in imgs:
params = ({'key' : self.key.decode('utf-8').encode('utf-8'), 'image' : open(img, "rb")})
socket = opener.open("http://api.imgur.com/2/upload.json", params)
read = json.loads(socket.read())
self.imageurl.append(read['upload']['links']['original'])
socket.close()
os.remove(img)
return True
except urllib2.URLError as s:
if self.tries < 3:
self.tries += 1
sys.stderr.write('Connection timed out, retrying to upload screenshots to imgur. This is try: ')
sys.stderr.write(str(self.tries))
sys.stderr.write('\n')
self.upload()
return True
开发者ID:dtreichler,项目名称:Pythonbits,代码行数:32,代码来源:pythonbits.py
示例18: _closesocket
def _closesocket(socket):
try:
socket.close()
return True
except:
print "Couldn't close the socket for some reason"
return False
开发者ID:webvictim,项目名称:imabot,代码行数:7,代码来源:teamspeak.py
示例19: handleGet
def handleGet(self, requestLineAsList, socket):
responseFile = self.hostedDirectory + requestLineAsList[1]
if os.path.isdir(responseFile):
responseFile = responseFile + "/"
if responseFile[-1] == '/':
responseFile = responseFile + "index.html"
content = ""
response = "HTTP/1.1 "
try:
print "Trying to open file: " + responseFile
file = open(responseFile, 'rb')
content = file.read()
response = response + "200 OK\r\n"
response = response + "Content-Length: " + str(len(content)) + "\r\n\r\n"
response = response + content
file.close()
#print "Response: ", response
except:
print "Exception"
response = response + "404 Not Found\r\n\r\n<html><body><h1>404 Not Found</h1></body></html>"
if socket.sendall(response) != None:
print "Failed to send"
print "Response successfully sent"
socket.close()
开发者ID:vekka,项目名称:inf-2301,代码行数:31,代码来源:webserver.py
示例20: packetized_receive
def packetized_receive(socket):
try:
message_len = socket.recv(16)
message_remaining = int(message_len)
message = ""
print "IN PACKETIZED RECEIVE RECEIVING: "+str(message_remaining)
while(message_remaining > 0):
if(message_remaining < 1024):
data = socket.recv(message_remaining)
if len(data) != message_remaining:
message_remaining -= len(data)
data = data + socket.recv(message_remaining)
message = message + data
message_remaining = 0
else:
data = socket.recv(1024)
if len(data) != 1024:
more = 1024 - len(data)
data = data + socket.recv(more)
message = message + data
message_remaining -= 1024
print "IN PACKETIZED RECEIVE RECEIVED: "+str(len(message))
return message
except Exception as e:
print "Peer disconnected, try again."
logging.info("Peer disconnected in packetized_receive:"+str(sys.exc_info()[0]))
socket.close()
开发者ID:rdwaite,项目名称:cs176b,代码行数:27,代码来源:echo_server.py
注:本文中的socket.close函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论