本文整理汇总了Python中socket.socket.close方法的典型用法代码示例。如果您正苦于以下问题:Python socket.close方法的具体用法?Python socket.close怎么用?Python socket.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket.socket
的用法示例。
在下文中一共展示了socket.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_mail
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def send_mail(sender_address, mail_server, receiver_address, message):
try:
client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
# set a 1 second timeout
client_socket.settimeout(1.0)
# connect to mail server
client_socket.connect((mail_server, 25))
def send(string):
"""Helper function: fix newlines, encode and send a string"""
final = string.replace("\n", "\r\n").encode("ascii")
print "Sending " + final + "..."
client_socket.send(final)
return 0
def recv_and_check(expected=250):
"""Helper function: recive reply and check it's ok"""
reply = client_socket.recv(2048)
print "Got: ", reply
code = int(reply.rstrip().split()[0])
if code != expected:
raise Exception(reply)
return 0
# get initial message from server
recv_and_check(220)
# send greeting
send("HELO {}\n".format(sender_address.split("@")[1]))
recv_and_check()
# set sender address
send("MAIL FROM: {}\n".format(sender_address))
recv_and_check()
# set receiver address
send("RCPT TO: {}\n".format(receiver_address))
recv_and_check()
# prepare to send message
send("DATA\n")
recv_and_check(354)
# send the message itself followed by terminator
send("{}\n.\n".format(message))
recv_and_check()
send("QUIT\n")
recv_and_check(221)
finally:
client_socket.close()
return 0
示例2: run_client
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def run_client(server_address, server_port):
# Ping a UDP pinger server running at the given address
try:
client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
# Time out after 1 second
client_socket.settimeout(1.0)
print("Pinging", str(server_address), "on port", server_port)
for i in range(10):
client_socket.sendto("".encode(), (server_address, server_port))
try:
time_start = time.time()
_, _ = client_socket.recvfrom(1024)
time_stop = time.time()
except socket.timeout:
print("Packet lost")
else:
print("RTT(Round trip time): {:.3f}ms".format((time_stop - time_start) * 1000))
finally:
client_socket.close()
return 0
示例3: get_rtt
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def get_rtt(server_address, server_port):
"""Ping a UDP ping server running at the given address
and show the ping status
"""
server = (server_address, server_port)
message = bytes("", 'UTF-8')
client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.settimeout(1.0)
try:
initial_time = current_milli_time()
client_socket.sendto(message, server)
client_socket.recvfrom(1024)
final_time = current_milli_time()
rtt = final_time - initial_time
except:
rtt = -1
client_socket.close()
return rtt
示例4: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def main():
register_builtin_interface()
server = Socket()
if len(sys.argv) > 1:
server_port = int(sys.argv[1])
else:
server_port = DEFAULT_PORT
print "Listening on port " + str(server_port)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(("", server_port))
server.listen(50)
Thread(target=process_event_queue).start()
print "\nAutobus has successfully started up."
try:
while True:
socket, address = server.accept()
connection = Connection(socket, address)
event_queue.put((connection.id, discard_args(connection.register)), block=True)
connection.start()
except KeyboardInterrupt:
print "KeyboardInterrupt received, shutting down"
event_queue.put((None, None), block=True)
print "Event queue has been notified to shut down"
except:
print "Unexpected exception occurred in the main loop, shutting down. Stack trace:"
print_exc()
event_queue.put((None, None), block=True)
print "Event queue has been notified to shut down"
server.close()
示例5: _recv
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def _recv(sock: socket.socket, size: int) -> bytes:
"""Secondary function to receive a specified amount of data."""
message = b''
while len(message) < size:
packet = sock.recv(size - len(message))
if not packet:
sock.close()
raise OSError("Nothing else to read from socket")
message += packet
return message
示例6: handlerequest
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def handlerequest(clientsocket: socket.socket):
conn = connecttodb()
cursor = conn.cursor()
tagid = bytes.decode(clientsocket.recv(3))
query = 'select * from tagdata where id={0}'.format(tagid)
cursor.execute(query)
s=[]
for (id, location, officehours, otherinfo, description) in cursor:
s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description]
s.insert(0, str(len(''.join(s)))+',')
clientsocket.send(bytes(''.join(s),encoding='utf8'))
clientsocket.close()
示例7: __init__
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def __init__(self):
# Set up the interrupt socket
interrupt_server = Socket()
interrupt_server.bind(("localhost", 0))
interrupt_server.listen(1)
self.interrupt_writer = Socket()
self.interrupt_writer.setblocking(False)
self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1])
self.interrupt_reader = interrupt_server.accept()
interrupt_server.shutdown(SHUT_RDWR)
interrupt_server.close()
self.interrupt_reader.setblocking(False)
self.interrupt_writer.setblocking(False)
示例8: _handle_connection
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def _handle_connection(self, connection: socket.socket, address: Any) -> None:
if self.ssl_options is not None:
assert ssl, "Python 2.6+ and OpenSSL required for SSL"
try:
connection = ssl_wrap_socket(
connection,
self.ssl_options,
server_side=True,
do_handshake_on_connect=False,
)
except ssl.SSLError as err:
if err.args[0] == ssl.SSL_ERROR_EOF:
return connection.close()
else:
raise
except socket.error as err:
# If the connection is closed immediately after it is created
# (as in a port scan), we can get one of several errors.
# wrap_socket makes an internal call to getpeername,
# which may return either EINVAL (Mac OS X) or ENOTCONN
# (Linux). If it returns ENOTCONN, this error is
# silently swallowed by the ssl module, so we need to
# catch another error later on (AttributeError in
# SSLIOStream._do_ssl_handshake).
# To test this behavior, try nmap with the -sT flag.
# https://github.com/tornadoweb/tornado/pull/750
if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
return connection.close()
else:
raise
try:
if self.ssl_options is not None:
stream = SSLIOStream(
connection,
max_buffer_size=self.max_buffer_size,
read_chunk_size=self.read_chunk_size,
) # type: IOStream
else:
stream = IOStream(
connection,
max_buffer_size=self.max_buffer_size,
read_chunk_size=self.read_chunk_size,
)
future = self.handle_stream(stream, address)
if future is not None:
IOLoop.current().add_future(
gen.convert_yielded(future), lambda f: f.result()
)
except Exception:
app_log.error("Error in connection callback", exc_info=True)
示例9: workWithUser
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def workWithUser(s : socket.socket):
global parser
global bUserConnect
bUserConnect = True
try:
while 1:
dataRecv = s.recv(1024).decode()
if (dataRecv == ''):
return
except socket.error:
return
finally:
bUserConnect = False
s.close()
示例10: run_server
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def run_server(server_port):
# Run UDP pinger server
try:
server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', server_port))
print("Ping server ready on port", server_port)
while True:
_, client_address = server_socket.recvfrom(1024)
server_socket.sendto("".encode(), client_address)
finally:
server_socket.close()
return 0
示例11: client_socket_thread
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def client_socket_thread(address, client_socket: socket.socket,
message_queue: queue.Queue,
new_observer_queue_queue: queue.Queue,
delete_observer_queue_queue: queue.Queue):
next_state = ''
tries = 0
if kicked == 1:
kick = 0 #reset kicking status
return
else:
nickname = address[0] + ':' + str(address[1]) #give them basic nickname of IP+port
userlist.append(nickname)
socketlist.append(client_socket) #add name to both socket list and user list
observer_queue = queue.Queue()
new_observer_queue_queue.put((client_socket, observer_queue))
client_sender(nickname, client_socket, message_queue, delete_observer_queue_queue)
client_socket.close()
示例12: call
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def call(self, *args, **kwargs):
"""
Remote call.
"""
socket = Socket(AF_INET, SOCK_STREAM)
socket.connect(self.address)
try:
method = Document()
method.name = self.name
method.args = args
method.kwargs = kwargs
socket.send(method.dump())
reply = socket.recv(4096)
result = Document()
result.load(reply)
return result
finally:
socket.close()
示例13: SocketStream
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
class SocketStream(Stream):
def __init__(self, port):
self.listener = Socket(AF_INET, SOCK_STREAM)
self.listener.bind(('', port))
def open(self):
self.listener.listen(1)
self.socket, address = self.listener.accept()
def read(self, size=1024):
return self.socket.recv(size)
def write(self, data):
self.socket.sendall(data)
def close(self):
self.socket.close()
self.listener.close()
示例14: get_page
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def get_page(server_address, request_string):
try:
client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_address, REMOTE_PORT))
client_socket.send(request_string.encode())
reply = bytes()
while True:
part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore")
# print part_body
if not len(part_body):
break
reply += part_body
finally:
client_socket.close()
return reply
示例15: wait_connect
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import close [as 别名]
def wait_connect(self):
if self.needQuit:
return
self.init_graphic()
self.informBoard = dashboard.InformBoard((10, 25), 15)
test = 0
server = Socket(socket.AF_INET, socket.SOCK_STREAM)
if not test:
while 1:
try:
server.bind(("", config.Port))
break
except socket.error as e:
self.inform(str(e))
for event in pygame.event.get():
if event.type == QUIT:
self.quit()
break
self.render_connection()
sleep(1)
server.listen(2)
server.settimeout(0.0)
player1 = Player(1, server)
else:
player1 = HumanPlayer(1)
if self.add_human:
player2 = HumanPlayer(2)
# add handler for human player
self.pyeventHandlers.append(player2)
else:
player2 = Player(2, server)
players = [player1, player2, None]
timer = pygame.time.Clock()
# wait until connected 2 players
finished = 0
player = players[finished]
try:
self.inform("waiting for AI to connect...")
while finished < 2:
for event in pygame.event.get():
if event.type == QUIT:
self.quit()
break
if self.needQuit:
break
if player.connect():
self.add_player(player)
self.inform("AI %s connected" % (player.name))
finished += 1
player = players[finished]
self.render_connection()
timer.tick(10)
except KeyboardInterrupt:
server.close()
return False
server.close()
return True