示例#1
0
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
0
 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)
    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
0
    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
0
 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
0
文件: speaker.py 项目: qsdj/ryu
 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
    def get_socket(self, addr):
        for socket in self.__sockets:
            #print(socket.getpeername())
            if socket.getpeername()[0] == addr:
                return socket

        print("Socket not found")
示例#8
0
 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
示例#9
0
 def __init__(self, server, socket):
     self.server = server
     self.socket = socket
     (self.host, self.port) = socket.getpeername()
     self.__readbuffer = ""
     self.__writebuffer = ""
     self.session = -1
示例#10
0
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
示例#11
0
    def __init__(self, config, eventloop, socket=None):
        self._eventloop = eventloop
        self._socket = socket
        self._remote = None
        self._fileno = None
        self._state = TCP_CONNECTION_STATE.DISCONNECTED
        self._read_buffer = None
        self._write_buffer = None
        self._last_active = 0

        if self._socket is not None:
            self._socket = socket
            self._remote = socket.getpeername()
            self._state = TCP_CONNECTION_STATE.CONNECTED
            self._fileno = self._socket.fileno()
            self._read_buffer = bytes()
            self._write_buffer = bytes()
            self._last_active = time.time()

            self._eventloop.register_file_event(
                self._fileno, EVENT_TYPE.READ | EVENT_TYPE.ERROR, 
                self._process_event)

        self._send_buffer_size = config['send_buffer_size']
        self._recv_buffer_size = config['recv_buffer_size']
        self._on_connected_transport = None
        self._on_disconnected_transport = None
        self._on_message_received_transport = None
 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
示例#13
0
 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
示例#14
0
文件: speaker.py 项目: alextwl/ryu
 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
示例#15
0
 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)
示例#16
0
    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()
示例#17
0
 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)
示例#18
0
 def __init__(self, server, socket):
     self.server = server
     self.socket = socket        
     (self.host, self.port) = socket.getpeername()
     self.__readbuffer = ""
     self.__writebuffer = ""
     self.session = -1
示例#19
0
	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)
示例#20
0
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)
示例#21
0
文件: server.py 项目: pmurias/iinic
 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)
示例#22
0
 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)
示例#23
0
文件: connection.py 项目: Xe/code
    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 = ""
示例#24
0
    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 = ""
示例#25
0
 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)
 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]))
示例#27
0
def board_cast(sock, message):
    for socket in connection_list:
        if socket != server_sock and socket != sock:
            try:
                socket.send(message)
            except:
                socket.close()
            print(str(socket.getpeername()), ' is offline')
            connection_list.remove(socket)
示例#28
0
    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)
示例#29
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(), socket)
     if _is_handshaking(socket):
         self._poller.register(socket, select.POLLIN | select.POLLOUT)
     else:
         self._poller.register(socket, select.POLLIN)
示例#30
0
文件: server.py 项目: jv503679/SE
def handler(signal, none):
        print("\r!! FERMETURE DU SERVEUR !!")
        for socket in socketlist:   #on ferme chaque socket disponible
                if socket != server and socket != server_web:
                        user = socket.getpeername()
                        print("{} a été déconnecté {}".format(client[user], user))
                socket.shutdown(SHUT_RDWR)
                socket.close()
        sys.exit()                  #on exit le programme
示例#31
0
def parse_from_socket(socket, ips_allowed_proxy):
    ip = socket.getpeername()[0]
    chunks = generator_recv(socket)

    # XXX: why? (different from gunicorn)
    if '*' in ips_allowed_proxy or ip in ips_allowed_proxy:
        return parse_maybe_proxy_and_state(chunks)

    return parse_and_state(chunks)
示例#32
0
 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)
示例#33
0
def send(socket, message):
    """Transmit a Channel Access message to an IOC via TCP"""
    from socket import error as socket_error
    addr, port = socket.getpeername()
    if DEBUG: debug("Send %s:%s %s" % (addr, port, message_info(message)))
    try:
        socket.sendall(message)
    except socket_error as error:
        if DEBUG: debug("Send failed: %r" % error)
示例#34
0
文件: common.py 项目: yumen/pyNgrok
 def run(self):
     if self.sck_side_A is not None and self.sck_side_B is not None:
         logger = logging.getLogger("logger")
         logger.info("%s start" % self.getName())
         set_sock_buff_size(self.sck_side_A)
         set_sock_buff_size(self.sck_side_B)
         #send cached data
         if self.cached_data_from_A:
             self.send_all(self.sck_side_B, self.cached_data_from_A)
         if self.cached_data_from_B:
             self.send_all(self.sck_side_A, self.cached_data_from_B)
         scks = (self.sck_side_A, self.sck_side_B)
         while self.forwarding:
             try:
                 readable, writeable, exceptional = select.select(
                     scks, [], scks, 1)
                 for s in readable:
                     data = recv(s, BUFFER_SIZE)
                     if len(data):
                         if s == self.sck_side_A:
                             #self.sck_side_B.sendall(data)
                             self.send_all(self.sck_side_B, data)
                         else:
                             #self.sck_side_A.sendall(data)
                             self.send_all(self.sck_side_A, data)
                     else:
                         # remote closed
                         self.forwarding = False
                         break
                 for s in exceptional:
                     socket.getpeername()
                     peer_addr, peer_port = s.getpeername()
                     local_addr, local_port = s.getsockname(self)
                     logger.error(
                         "socket in exceptional %s:%d->%s:%d" %
                         (local_addr, local_port, peer_addr, peer_port))
                     self.forwarding = False
                     break
             except socket.error, e:
                 logger.error(traceback.format_exc())
                 self.forwarding = False
             except Exception, e:
                 logger.error(traceback.format_exc())
                 self.forwarding = False
 def __init__(self, server, socket):
     self.server = server
     self.socket = socket
     self.channels = {}  # irc_lower(Channel name) --> Channel
     self.nickname = None
     self.user = None
     self.realname = None
     if self.server.ipv6:
         (self.host, self.port, _, _) = socket.getpeername()
     else:
         (self.host, self.port) = socket.getpeername()
     self.__timestamp = time.time()
     self.__readbuffer = ""
     self.__writebuffer = ""
     self.__sent_ping = False
     if self.server.password:
         self.__handle_command = self.__pass_handler
     else:
         self.__handle_command = self.__registration_handler
示例#36
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(),
                                                   socket)
     if _is_handshaking(socket):
         self._poller.register(socket, select.POLLIN | select.POLLOUT)
     else:
         self._poller.register(socket, select.POLLIN)
示例#37
0
文件: server.py 项目: jv503679/SE
def search_user_socket(username, socklist):
        user = [s for s, c in client.items() if c == username]
        if(user):
                user = user[0]
                for socket in socklist:
                        if socket != server and socket != server_web:
                                u = socket.getpeername()
                                if u == user:
                                        return socket
        return False
示例#38
0
 def get_remote_host_ip(self, user_fd):
     if user_fd in self.user_fd_to_socket_fd.keys():
         socket = self.socket_fileno_info[
             self.user_fd_to_socket_fd[user_fd]]['socket']
         try:
             return socket.getpeername()[0]
         except Exception as e:
             logger.error(traceback.format_exc())
     else:
         return None
示例#39
0
def getMsg(socket):
	global list
	try:
		ret=socket.recv(4096)
		socket.settimeout(.1)
		if str(ret) == "/quit" or str(ret) == "/Quit":
			host,port=socket.getpeername()
			print ("["+str(host)+" :"+str(port)+"] ha salido.")
			list.remove(socket)
			socket.close()
			return None 
		return ret
	except:
		host,port=socket.getpeername()
		
		print ("["+str(host)+" :"+str(port)+"] ha salido.")		

		list.remove(socket)
		return None 
示例#40
0
文件: server.py 项目: jv503679/SE
def send_to_all_users (initial_socket, username, message):
        for socket in socketlist:   #Pour tous les sockets...
                if socket != server and socket != server_web and socket != initial_socket :  #... qui ne sont pas le serveur ni le client ayant envoyé le message...
                        try:
                                socket.send(username + message)   #on envoie le message
                        except:  #erreur si le socket n'existe plus mais est toujours ouvert... donc on le ferme et on le remove de la liste
                                socket.close()
                                user = socket.getpeername()
                                del client[user]
                                socketlist.remove(socket)
示例#41
0
 def __init__(self, server: Server, socket: socket.socket):
     self.server = server
     self.socket = socket
     self.nickname = None
     self.user = None
     self.realname = None
     (self.host, self.port) = socket.getpeername()
     self.channels = set()
     self._sendmsg = ''
     self.greeted = False
示例#42
0
 def __init__(self, socket):
     threading.Thread.__init__(self)
     (self.ip, self.port) = socket.getpeername()
     self.socket = common.VerboseSocket(socket, "C " + str(self.ip) + ":" + str(self.port))
     self.socket.print_func = print if configuration.verbosity >= 1 else common.null_print
     
     self.running = True
     self.username = None
     self.buffer = []
     self.log_file = open("server.log", "a")
示例#43
0
def read_success_packet(socket, data):
    global ack_receivers
    global current_window
    global number_of_clients
    global ready_to_transmit

    packet = SuccessPacket.unpack(data[:8])

    # Indicate which receiver acknowledged success of receipt
    if (socket.getpeername() not in ack_receivers
            and packet[3] == current_window):
        ack_receivers.append(socket.getpeername())

    # Determine if all receivers received the file
    if all_ack_received(ack_receivers,
                        number_of_clients) and current_window == last_window:
        # Handle edge case, where the last window is the first winidow
        if (ready_to_transmit):
            print >> sys.stderr, "File successfully sent."
            sys.exit(0)

    # Wait for acknoledgement of start of stream packet receipt from all the clients
    if (ready_to_transmit == False
            and all_ack_received(ack_receivers, number_of_clients)):
        # Send the packets in the 0th window
        send_data(udp_socket, file_name, current_window, protocol.window_size)

        # Send end of stream
        send_eos(sockets, current_window)

        ack_receivers = []
        ready_to_transmit = True

    # When clients are ready, send the file
    if (ready_to_transmit == True
            and all_ack_received(ack_receivers, number_of_clients)):
        # Moving to the next window
        current_window += 1

        ack_receivers = []

        send_window()
示例#44
0
 def __init__(self, socket, nick):
     """
     init CLient object
     :param socket: the socket connection with client
     :param nick: the nickname of the client, (default = socket addr:port)
     """
     self.socket = socket
     if nick:
         self.nick = nick
     else:
         self.nick = str(socket.getpeername())
示例#45
0
    def __init__(self, socket):
        super().__init__()
        self.conn = socket
        self.buffer_size = 2048

        self.room = None
        self.registered = False
        self.id = socket.getpeername()[0]
        self.transgressions = 0
        print("[+] New server socket thread started for " + IP + ":" +
              str(PORT))
示例#46
0
def sendIpListToAll(ip):
    for socket in socketDict.values():
        ipList = list(socketDict.keys())
        socketip = socket.getpeername()
        for index, item in enumerate(ipList):
            print('checking: ', item, ' against: ', socketip[0] + '/' + str(socketip[1]))
            if item == (socketip[0] + '/' + str(socketip[1])):
                ipList[index] = item + ' -- ME'
                break
        jsonToSend = {"action": 'ipList', "ipList": ipList}
        sendJsonToSocket(socket, jsonToSend)
示例#47
0
def client_disconnect(socket, addr):
    fd = socket.fileno()
    with object_lock:
        q = clients.get(fd, None)['queue']
        if q:
            q.put(None)
            del clients[fd]

        addr = socket.getpeername()
        print('Klient {} zostal rozlaczony'.format(addr))
        socket.close()
示例#48
0
文件: util.py 项目: jinty/zc.resumelb
 def connected(self, socket, addr=None):
     if addr is None:
         addr = socket.getpeername()
     logger.info('worker connected %s', addr)
     self.addr = addr
     self.readers = {}
     writeq = ByteSizedQueue(queue_size_bytes)
     gevent.Greenlet.spawn(writer, writeq, socket, self)
     self.put = writeq.put
     self.is_connected = True
     return self.readers
示例#49
0
    def __init__(self, socket=None):
        """
        Arguments:
            socket -- (optionel) un object socket valide
        """
        log.info("Initializing connection")

        self.socket = socket
        if self.socket is not None:
            # XXX An improvement would be to check the validity of the socket.
            self.socket.setblocking(0)
            log.debug("peername %s" % str(socket.getpeername()))
示例#50
0
	def __init__(self, socket):
		self.socket = socket
		self.address = socket.getpeername()
		self.read_buffer = ""
		self.write_buffer = ""
		self.running = True
		self.last_activity = time.time()

		self.init()

		self.logger = logging.getLogger()
		self.logger.info("%s:%s - Connection" % (self.address[0], self.address[1]))
    def pollOnce(self):
        """
        Poll for incoming data once.
        """
        try:
            rlist = select.select([self.listenerSocket] + self.connections.keys(), [], [])[0]
        except:
            # It's likely that one or more of our sockets is no longer valid.

            # If it's our listener socket, we can't continue:
            try:
                self.listenerSocket.fileno()
            except:
                self.notify.error('The listener socket is no longer valid!')

            # Otherwise, discard the faulty sockets, and wait for the next poll
            # iteration:
            for socket in self.connections.keys():
                try:
                    socket.fileno()
                    socket.getpeername()
                except:
                    del self.connections[socket]
                    if socket in self.dispatchThreads:
                        del self.dispatchThreads[socket]

            return

        if self.listenerSocket in rlist:
            self.handleNewConnection()

        for socket in rlist:
            connection = self.connections.get(socket)
            if connection is None:
                continue
            if socket in self.dispatchThreads:
                continue
            self.dispatchThreads[socket] = threading.Thread(
                target=self.dispatchThread, args=[socket])
            self.dispatchThreads[socket].start()
示例#52
0
 def __init__(self, socket):
     gps.GPSTransport.__init__(self)
     self.address = '%s:%s' % socket.getpeername()
     self.localaddress = '%s:%s' % socket.getsockname()
     self.socket = socket
     self.closeReason = None
     self.socketStatsEnabled = prefs.GetValue('socketStatsEnabled', False)
     self.statsBytesReadPerPacket = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESREADPERPACKET_PERIODS)
     self.statsBytesWrittenPerPacket = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESWRITTENPERPACKET_PERIODS)
     self.statsBytesRead = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESREAD_PERIODS)
     self.statsBytesWritten = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESWRITTEN_PERIODS)
     self.statsPacketsRead = macho.EWMA.FromSampleCounts(GPSSTATS_PACKETSREAD_PERIODS)
     self.statsPacketsWritten = macho.EWMA.FromSampleCounts(GPSSTATS_PACKETSWRITTEN_PERIODS)