• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.getpeername函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.getpeername函数的典型用法代码示例。如果您正苦于以下问题:Python getpeername函数的具体用法?Python getpeername怎么用?Python getpeername使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了getpeername函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()]
开发者ID:dduong1,项目名称:Simple-messenger,代码行数:28,代码来源:serv.py


示例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)
开发者ID:jhedtmann,项目名称:avnav,代码行数:35,代码来源:socketwriter.py


示例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)
开发者ID:Comp-UFSCar,项目名称:computer-networks,代码行数:27,代码来源:supernode.py


示例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)
开发者ID:zcbgit,项目名称:GameServer,代码行数:12,代码来源:worker.py


示例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
开发者ID:alfredocdmiranda,项目名称:chat,代码行数:52,代码来源:server.py


示例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
开发者ID:ardisragen,项目名称:AutomaticConfigurationRouteFlow,代码行数:7,代码来源:workers.py


示例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
开发者ID:alextwl,项目名称:ryu,代码行数:27,代码来源:speaker.py


示例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)
开发者ID:myOvirt,项目名称:vdsm,代码行数:7,代码来源:protocoldetector.py


示例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
开发者ID:alfredocdmiranda,项目名称:chat,代码行数:34,代码来源:server.py


示例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
开发者ID:IPA-ZONE,项目名称:PRMasterServer,代码行数:7,代码来源:GPC4.py


示例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()
开发者ID:arellanon,项目名称:Taller-II,代码行数:31,代码来源:ServerChat.py


示例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
开发者ID:asafliv,项目名称:SimplePythonChat,代码行数:30,代码来源:snakeChatServer.py


示例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)
开发者ID:boruiwang,项目名称:Python,代码行数:47,代码来源:chatServer.py


示例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)
开发者ID:Comp-UFSCar,项目名称:computer-networks,代码行数:8,代码来源:supernode.py


示例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)
开发者ID:famargon,项目名称:chat,代码行数:8,代码来源:pyServerChat.py


示例16: __init__

 def __init__(self, socket, server):
     self.socket = socket
     self.server = server
     self.peer = '%s:%d' % socket.getpeername()
     self.connected = True
     self.uniq_id = random.randint(1,65534)
     self.resetState()
     logging.info('peer %s is connected', self.peer)
开发者ID:Neverous,项目名称:ii-iinic,代码行数:8,代码来源:server.py


示例17: __init__

    def __init__(self, socket, parent):
        self.link = socket
        self.queue = Queue.Queue()
        self.poller = parent.poller
        self.parent = parent
        self.peername = socket.getpeername()

        self.tbuf = ""
开发者ID:Xe,项目名称:code,代码行数:8,代码来源:connection.py


示例18: _select_loop

    def _select_loop(self):
        """
        This is the select loop.
        we wait for any socket to wake up.
        If this is the server-socket, we accept the new connection. If this is a new message from a client,
        we handle the request and finally try to send all clients the messages we need to send them.
        We assume we don't need to send any data as long as we did not receive any request.
        :return:
        """
        self.log(None, "Start Loop", None)

        while True:

            readable, writable, errored = select.select(self.read_list, self.write_list, [])

            for socket in readable:
                if socket is self.serversocket:

                    ## New connection, add it to the client list and read_list
                    client_socket, address = self.serversocket.accept()
                    client_socket.settimeout(0)

                    self.read_list.append(client_socket)

                    client = SocketClient(client_socket)
                    self.Clients.append(client)

                    self.log(client, "Event", "New connection")
                else:

                    ### Get the client object by socket
                    client = self._getClient(socket)
                    if client is None:
                        self.log(None, "Client not found", socket.getpeername(), FRedis.LOG_LEVEL_ERROR)
                        continue

                    ### Try to receive data from the readable socket.
                    messages = self._receiveEx(client)

                    ### Readable socket should not return 0 bytes.
                    ### in that case, we terminate the connection.
                    if (messages is None):
                        self.log(client, "Event", "Client dropped")
                        self._removeClient(client)
                        self.read_list.remove(socket)
                        socket.close()

                        continue

                    ### We may receive many request from the connector,
                    ### Handle client with received requests
                    for someMessage in messages:
                        self._handleClient(client, someMessage)

                    ### Push all messages to clients
                    for client in self.Clients:
                        self._sendEx(client)
开发者ID:roniiw,项目名称:exp,代码行数:57,代码来源:fredis_server.py


示例19: __init__

 def __init__(self, socket):
     threading.Thread.__init__(self)
     threads.append(self)
     self.login = False
     self.lastactive = time.time()
     self.s = socket
     self.addr = socket.getpeername()
     self.invi = False
     print('connected with '+self.addr[0]+':'+str(self.addr[1]))
开发者ID:Alomin,项目名称:computer_network_client_server,代码行数:9,代码来源:Server.py


示例20: connectionSuccess

 def connectionSuccess(self):
     socket = self.sub.socket
     self.sub.state = "dead"
     del self.sub
     self.state = "connected"
     self.cancelTimeout()
     p = self.factory.buildProtocol(self.buildAddress(socket.getpeername()))
     self.transport = self.transport_class(socket, p, self)
     p.makeConnection(self.transport)
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:9,代码来源:client.py



注:本文中的socket.getpeername函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.getprotobyname函数代码示例发布时间:2022-05-27
下一篇:
Python socket.getnameinfo函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap