本文整理汇总了Python中socket.getpeername函数的典型用法代码示例。如果您正苦于以下问题:Python getpeername函数的具体用法?Python getpeername怎么用?Python getpeername使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getpeername函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: broadcast
def broadcast (server_socket, sock, message, msgtype):
#message = bytes(message,'UTF-8')
sjson = json.dumps(message.__dict__)
for socket in SOCKET_LIST:
# send the message to all peers
if msgtype ==1:
if socket != server_socket and socket != sock :
try :
socket.send(bytes(sjson, 'utf-8'))
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
del SOCKET_LIST_user[socket.getpeername()]
# send message to self
else:
if socket != server_socket and socket == sock :
try :
socket.send(bytes(sjson, 'utf-8'))
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
del SOCKET_LIST_user[socket.getpeername()]
示例2: client
def client(self,socket,addr):
infoName="SocketWriter-%s"%(unicode(addr),)
self.setName("[%s]%s-Writer %s"%(AVNLog.getThreadId(),self.getName(),unicode(addr)))
self.setInfo(infoName,"sending data",AVNWorker.Status.RUNNING)
if self.getBoolParam('read',False):
clientHandler=threading.Thread(target=self.clientRead,args=(socket, addr))
clientHandler.daemon=True
clientHandler.start()
filterstr=self.getStringParam('filter')
filter=None
if filterstr != "":
filter=filterstr.split(',')
try:
seq=0
socket.sendall("avnav_server %s\r\n"%(VERSION))
while True:
hasSend=False
seq,data=self.feeder.fetchFromHistory(seq,10)
if len(data)>0:
for line in data:
if NMEAParser.checkFilter(line, filter):
socket.sendall(line)
hasSend=True
else:
time.sleep(0.1)
pass
if not hasSend:
#just throw an exception if the reader potentially closed the socket
socket.getpeername()
except Exception as e:
AVNLog.info("exception in client connection %s",traceback.format_exc())
AVNLog.info("client disconnected")
socket.close()
self.removeHandler(addr)
self.deleteInfo(infoName)
示例3: handle_upload
def handle_upload(self, socket, filename):
""" recebe um arquivo de um cliente ou supernó """
# se estiver "sujo" com diretórios, extrai só o nome do arquivo
filename = split(filename)[-1]
filepath = join(self.fileroot, filename)
try:
if isfile(filepath):
# arquivo já existe
raise BaseException
# informa que pode receber
socket.send('ok')
print "Recebendo %s de (%s:%s)" % (filename, socket.getpeername()[0], socket.getpeername()[1])
file = open(filepath, 'wb')
while 1:
file_data = socket.recv(BUFFER_SIZE)
if not file_data:
break
file.write(file_data)
file.close()
self.file_list.append(filename)
except IOError:
print "Erro de acesso ao arquivo %s" % filepath
except:
# informa o requisitante que o arquivo já existe
socket.send('no')
self.close_conn(socket)
示例4: _close_socket
def _close_socket(self, socket):
if socket:
self._lock.acquire()
if socket in self._conn_sockets:
log = "%s:%d is closed" % socket.getpeername()
socket.close()
del self._conn_sockets[socket]
else:
log = "%s:%d is not existed!" % socket.getpeername()
self._lock.release()
self._logger.info(log)
示例5: nick
def nick(self, command, arguments, socket):
msgs = []
if not arguments:
#ERR_NEEDMOREPARAMS
dest = socket
msg = "401 {0} :Not enough parameters".format(command)
else:
nickname = arguments[0][0]
dest = socket
if self.validate_grammar(nickname, "nick"):
if nickname in self.clients_nick:
#ERR_NICKNAMEINUSE
msg = "404 {0} :Nickname is already in use".format(nickname)
else:
if socket in self.clients_socket:
if nickname == "admin" and socket.getpeername()[0] != "127.0.0.1":
#ERR_NOPERMISSION
msg = "402 :No permission"
else:
#Verify and change nick.
old_nickname = self.clients_socket[socket].nickname
del self.clients_nick[old_nickname]
self.clients_socket[socket].nickname = nickname
self.clients_nick[nickname] = self.clients_socket[socket]
for c in self.channels:
if old_nickname in self.channels[c].users:
index = self.channels[c].users.index(old_nickname)
self.channels[c].users[index] = nickname
if old_nickname == self.channels[c].owner:
self.channels[c].owner = nickname
#RPL_NICKNAMECHANGED
msg = "306"
else:
if nickname == "admin" and socket.getpeername()[0] != "127.0.0.1":
#ERR_NOPERMISSION
msg = "402 :No permission"
else:
#Registering user
self.clients_socket[socket] = Client(nickname, socket)
self.clients_nick[nickname] = self.clients_socket[socket]
#RPL_NICKNAMECHANGED
msg = "306"
else:
#ERR_NAMEINVALID
msg = "403 {0} :Invalid name".format(nickname)
dest = socket
msgs.append([msg, dest])
return msgs
示例6: _do_accept
def _do_accept (self, loop, socket):
addr = socket.getpeername()
self._debug("accepting %s:%i" % addr)
out = loop.new_worker(socket = socket,
_worker_type = self.child_worker_type,
**self.child_args)
return out
示例7: __init__
def __init__(self, socket, signal_bus, is_reactive_conn=False):
# Validate input.
if socket is None:
raise ValueError('Invalid arguments passed.')
activity_name = ('BgpProtocol %s, %s, %s' % (
is_reactive_conn, socket.getpeername(), socket.getsockname())
)
Activity.__init__(self, name=activity_name)
# Intialize instance variables.
self._peer = None
self._recv_buff = ''
self._socket = socket
self._signal_bus = signal_bus
self._holdtime = None
self._keepalive = None
self._expiry = None
# Add socket to Activity's socket container for managing it.
if is_reactive_conn:
self._asso_socket_map['passive_conn'] = self._socket
else:
self._asso_socket_map['active_conn'] = self._socket
self._open_msg = None
self.state = BGP_FSM_CONNECT
self._is_reactive = is_reactive_conn
self.sent_open_msg = None
self.recv_open_msg = None
self._is_bound = False
示例8: _add_connection
def _add_connection(self, socket):
host, port = socket.getpeername()
self.log.debug("Adding connection from %s:%d", host, port)
socket.setblocking(0)
self._pending_connections[socket.fileno()] = (time.time(),
socket)
self._poller.register(socket, self.READ_ONLY_MASK)
示例9: kill
def kill(self, command, arguments, socket):
msgs = []
nickname = self.clients_socket[socket].nickname
if not arguments:
#ERR_NEEDMOREPARAMS
dest = socket
msg = "401 {0} :Not enough parameters".format(command)
msgs.append([msg, dest])
else:
kill_nick = arguments[0][0]
if socket.getpeername()[0] != "127.0.0.1":
#ERR_NOPERMISSION
dest = socket
msg = "402 :No permission"
msgs.append([msg, dest])
else:
if kill_nick in self.clients_nick:
dest = self.clients_nick[kill_nick].socket
for c in self.channels:
self.quit_chan(dest, c)
if len(arguments) > 1:
msg = "You were kicked because '{0}'.".format(arguments[1][0])
else:
msg = "You were kicked because 'No reason'."
send(dest, msg)
self.disconnect_client(self.clients_nick[kill_nick].socket)
else:
#ERR_NOSUCHNICK
msg = "405 :No such nick"
dest = socket
msgs.append([msg, dest])
return msgs
示例10: __init__
def __init__(self, server, socket):
self.server = server
self.socket = socket
(self.host, self.port) = socket.getpeername()
self.__readbuffer = ""
self.__writebuffer = ""
self.session = -1
示例11: esperando_conexiones
def esperando_conexiones(self):
self.server_socket.listen(self.listen)
# Añadimos socket server a la lista
self.CONNECTION_LIST.append(self.server_socket)
while True:
# Obtener la lista sockets que están listos para ser leídos a través de selección
read_sockets,write_sockets,error_sockets = select.select(self.CONNECTION_LIST,[],[])
for socket in read_sockets:
# Nueva conexion
if socket == self.server_socket:
# Hay una nueva conexión recibida
client_socket, addr = self.server_socket.accept()
self.CONNECTION_LIST.append(client_socket)
print "Cliente (%s, %s) conectado" % addr
self.enviar_msg(client_socket, "Ingreso: [%s:%s].\n" % addr)
# Mensaje desde algun cliente chat
else:
# Datos del cliente
try:
data = socket.recv(self.recv_buffer)
if data:
self.enviar_msg(socket, "\r" + '<' + str(socket.getpeername()) + '> ' + data)
except:
self.enviar_msg(socket, "Cliente (%s, %s) desconectado." % addr)
print "Cliente (%s, %s) desconectado." % addr
socket.close()
self.CONNECTION_LIST.remove(socket)
continue
self.server_socket.close()
示例12: parse_sent_data
def parse_sent_data(data, socket):
if data[0:9] == 'userName/':
# Username the client chose for himself
user_connected = data[9:len(data)]
dup = False
# Check if it is a duplicate
for key, val in user_dic:
if user_dic[key, val] == user_connected:
dup = True;
break
if (dup):
socket.sendall(str("DUPNAME"))
return None
# Add to the client dicionary the userName as value and the sockname as key
update_user_list(socket.getpeername(), user_connected)
return None
elif data[0:10] == '--userList':
# User requested the user list of the site
user_names_to_return = [];
for (sock_String, port_value) in user_dic:
user_names_to_return.append(user_dic[(sock_String, port_value)])
socket.sendall(str(user_names_to_return))
return None
elif data == "CLOSEDCONNECTION":
# Client has signaled it is disconnecting
remove_client(socket)
return None
else:
return data
示例13: setUpServer
def setUpServer(self, socket):
# create server socket waiting for the connection
server_sock = socket.socket()
server_sock.bind((self.host, self.port))
server_sock.listen(1)
self.socket_list.append(server_sock)
print "Server starts from port " + str(self.port)
print "waiting for a connection ..."
while True:
'''
Select() method can select sockets from the pool when the socket is ready.
Socket_list stores all the readable sockets.
Connected_list stores all the writable sockets, in our case,
it is always empty, because we want the client can receive data
after the connection instead of sending data to the server.
'''
ready_2_read, ready_2_send, in_error = select.select(self.socket_list,
self.connected_list,
[])
for socket in ready_2_read:
# case 1, a server socket is ready for a connection
if socket == server_sock:
connection, client_address = socket.accept()
print "new connection from " + str(client_address)
# add the client socket to readable list for sending the data
self.socket_list.append(connection)
message = "[ %s ] entered our chat room.\n" % str(client_address)
self.broadcast(server_sock, connection, message)
# case 2, receive data from the client
else:
data = socket.recv(1024)
if data:
message = data
self.storeInDB(data, socket)
self.broadcast(server_sock, socket, message)
else:
print "closing " + str(socket.getpeername()) + " after reading no data\n"
self.socket_list.remove(socket)
# delete user dict
if socket.getpeername()[1] in self.user:
del self.user[socket.getpeername()[1]]
message = "[ %s ] is offline\n" % str(socket.getpeername())
self.broadcast(server_sock, socket, message)
示例14: handle_list_request
def handle_list_request(self, socket):
""" envia a lista de arquivos disponíveis (como um objeto) """
print "Enviando lista de arquivos a (%s:%s)" % socket.getpeername()
# fazendo dump do objeto (serializando) para bytes
list_dump = pickle.dumps(self.file_list, -1)
socket.sendall(list_dump)
# atendeu à requisição, fecha a conexão
self.close_conn(socket)
示例15: broadcast
def broadcast(socket,message):
global list
global s
host, port = socket.getpeername()
msg = "[%s:%s]: %s" % (str(host), str(port), str(message))
for sock in list:
if sock != socket and sock != s:
sock.send(msg)