本文整理汇总了Python中socket.close函数的典型用法代码示例。如果您正苦于以下问题:Python close函数的具体用法?Python close怎么用?Python close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了close函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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')
示例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)
示例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)
示例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()
示例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
示例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()
示例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()
示例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)
示例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
示例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()
示例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)
示例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()
示例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)
示例15: send_data
def send_data(socket):
while True:
data = input()
socket.send(data.encode('utf-8'))
if(data == 'exit'):
socket.close()
break