Sujet n°7867
Posté par Titi6 le 19 Sep - 11:20 (2010)
Titre : Système d'échange en temps réel
Bonjour à tout et à toute


Voilà j'ai programmer un nouveau système d'échange en temps réel (oui en temps réel  Clin d'œil foireux  )


Mais (et oui un mais) je n'arrive pas à utiliser la fonction ajouter_pokemon_param( hash )
c'est le seul petit problème a régler et mon système est fonctionnel aidé moi please ^^




pour le septique une vidéo ^^






merci à Denis Bros pour le script qui ma permit de faire ce système
./3275-serveur-pour-RMXP-executable-seu…


Les codes et la demo 



Win32 Library *

Spoiler
#==============================================================================
# ■ Win32
#------------------------------------------------------------------------------
#  Handles numerical based data.
#==============================================================================


module Win32


  #--------------------------------------------------------------------------
  # ● Retrieves data from a pointer.
  #--------------------------------------------------------------------------
  def copymem(len)
    buf = "\0" * len
    Win32API.new("kernel32", "RtlMoveMemory", "ppl", "").call(buf, self, len)
    buf
  end
  
end


# Extends the numeric class.
class Numeric
  include Win32
end


# Extends the string class.
class String
  include Win32
end


#==============================================================================
# ■ Winsock
#------------------------------------------------------------------------------
#  Maps out the functions held in the Winsock DLL.
#==============================================================================


module Winsock


  DLL = "ws2_32"


  def self.accept(*args)
    Win32API.new(DLL, "accept", "ppl", "l").call(*args)
  end


  def self.bind(*args)
    Win32API.new(DLL, "bind", "ppl", "l").call(*args)
  end


  def self.closesocket(*args)
    Win32API.new(DLL, "closesocket", "p", "l").call(*args)
  end  
 
  def self.connect(*args)
    Win32API.new(DLL, "connect", "ppl", "l").call(*args)
  end    


  def self.gethostbyaddr(*args)
    Win32API.new(DLL, "gethostbyaddr", "pll", "l").call(*args)
  end
 
  def self.gethostbyname(*args)
    Win32API.new(DLL, "gethostbyname", "p", "l").call(*args)
  end


  def self.gethostname(*args)
    Win32API.new(DLL, "gethostname", "pl", "").call(*args)
  end


  def self.getservbyname(*args)
    Win32API.new(DLL, "getservbyname", "pp", "p").call(*args)
  end


  def self.htonl(*args)
    Win32API.new(DLL, "htonl", "l", "l").call(*args)
  end
 
  def self.htons(*args)
    Win32API.new(DLL, "htons", "l", "l").call(*args)
  end


  def self.inet_addr(*args)
    Win32API.new(DLL, "inet_addr", "p", "l").call(*args)
  end


  def self.inet_ntoa(*args)
    Win32API.new(DLL, "inet_ntoa", "l", "p").call(*args)
  end  
  
  def self.gethostname(*args)
    Win32API.new(DLL, "gethostname", "pl", "").call(*args)
  end


  def self.listen(*args)
    Win32API.new(DLL, "listen", "pl", "l").call(*args)
  end


  def self.recv(*args)
    Win32API.new(DLL, "recv", "ppll", "l").call(*args)
  end
  
  def self.select(*args)
    Win32API.new(DLL, "select", "lpppp", "l").call(*args)
  end
 
  def self.send(*args)
    Win32API.new(DLL, "send", "ppll", "l").call(*args)
  end
  
  def self.setsockopt(*args)
    Win32API.new(DLL, "setsockopt", "pllpl", "l").call(*args)
  end  


  def self.shutdown(*args)
    Win32API.new(DLL, "shutdown", "pl", "l").call(*args)
  end
  
  def self.socket(*args)
    Win32API.new(DLL, "socket", "lll", "l").call(*args)  
  end
  
  def self.WSAGetLastError(*args)
    Win32API.new(DLL, "WSAGetLastError", "", "l").call(*args)
  end
 
end



Socket Library *
Spoiler
#==============================================================================
# ■ Socket
#------------------------------------------------------------------------------
#  Creates and manages sockets.
#   Version   Date          Auteur        Commentaires
#   1.02      07/01/2007    Tonyryu       Optimisation du code
#   1.03      12/02/2008    Tonyryu       Correction setTimeout
#
#==============================================================================


class Socket


  #--------------------------------------------------------------------------
  # ● Constants
  #--------------------------------------------------------------------------
  AF_UNSPEC                 = 0  
  AF_UNIX                   = 1
  AF_INET                   = 2
  AF_IPX                    = 6
  AF_APPLETALK              = 16


  PF_UNSPEC                 = 0  
  PF_UNIX                   = 1
  PF_INET                   = 2
  PF_IPX                    = 6
  PF_APPLETALK              = 16


  SOCK_STREAM               = 1
  SOCK_DGRAM                = 2
  SOCK_RAW                  = 3
  SOCK_RDM                  = 4
  SOCK_SEQPACKET            = 5
  
  IPPROTO_IP                = 0
  IPPROTO_ICMP              = 1
  IPPROTO_IGMP              = 2
  IPPROTO_GGP               = 3
  IPPROTO_TCP               = 6
  IPPROTO_PUP               = 12
  IPPROTO_UDP               = 17
  IPPROTO_IDP               = 22
  IPPROTO_ND                = 77
  IPPROTO_RAW               = 255
  IPPROTO_MAX               = 256


  SOL_SOCKET                = 65535
  
  SO_DEBUG                  = 1
  SO_REUSEADDR              = 4
  SO_KEEPALIVE              = 8
  SO_DONTROUTE              = 16
  SO_BROADCAST              = 32
  SO_LINGER                 = 128
  SO_OOBINLINE              = 256
  SO_RCVLOWAT               = 4100
  SO_SNDTIMEO               = 4101
  SO_RCVTIMEO               = 4102
  SO_ERROR                  = 4103
  SO_TYPE                   = 4104
  SO_SNDBUF                 = 4097
  SO_RCVBUF                 = 4098
  SO_SNDLOWAT               = 4099
  
  TCP_NODELAY               = 1
  
  MSG_OOB                   = 1
  MSG_PEEK                  = 2
  MSG_DONTROUTE             = 4
  
  IP_OPTIONS                = 1
  IP_DEFAULT_MULTICAST_LOOP = 1
  IP_DEFAULT_MULTICAST_TTL  = 1
  IP_MULTICAST_IF           = 2
  IP_MULTICAST_TTL          = 3
  IP_MULTICAST_LOOP         = 4
  IP_ADD_MEMBERSHIP         = 5
  IP_DROP_MEMBERSHIP        = 6
  IP_TTL                    = 7
  IP_TOS                    = 8
  IP_MAX_MEMBERSHIPS        = 20


  EAI_ADDRFAMILY            = 1
  EAI_AGAIN                 = 2
  EAI_BADFLAGS              = 3
  EAI_FAIL                  = 4
  EAI_FAMILY                = 5
  EAI_MEMORY                = 6
  EAI_NODATA                = 7
  EAI_NONAME                = 8
  EAI_SERVICE               = 9
  EAI_SOCKTYPE              = 10
  EAI_SYSTEM                = 11
  EAI_BADHINTS              = 12
  EAI_PROTOCOL              = 13
  EAI_MAX                   = 14


  AI_PASSIVE                = 1
  AI_CANONNAME              = 2
  AI_NUMERICHOST            = 4
  AI_MASK                   = 7
  AI_ALL                    = 256
  AI_V4MAPPED_CFG           = 512
  AI_ADDRCONFIG             = 1024
  AI_DEFAULT                = 1536
  AI_V4MAPPED               = 2048
  
  # Variable de latence
  $socket_tps_action = 0        # Temps d'activité du socket
  
  #--------------------------------------------------------------------------
  # ● Returns the associated IP address for the given hostname.
  #--------------------------------------------------------------------------  
  def self.getaddress(host)
    gethostbyname(host)[3].unpack("C4").join(".")
  end
  
  #--------------------------------------------------------------------------
  # ● Returns the associated IP address for the given hostname.
  #--------------------------------------------------------------------------  
  def self.getservice(serv)
    case serv
    when Numeric
      return serv
    when String
      return getservbyname(serv)
    else
      raise "Please us an interger or string for services."
    end
  end


  #--------------------------------------------------------------------------
  # ● Returns information about the given hostname.
  #--------------------------------------------------------------------------
  def self.gethostbyname(name)
    #raise SocketError::ENOASSOCHOST 
    return SocketError.check if (ptr = Winsock.gethostbyname(name)) == 0
    host = ptr.copymem(16).unpack("iissi")
    [host[0].copymem(64).split("\0")[0], [], host[2], host[4].copymem(4).unpack("l")[0].copymem(4)]
  end
  
  #--------------------------------------------------------------------------
  # ● Returns the user's hostname.
  #--------------------------------------------------------------------------  
  def self.gethostname
    buf = "\0" * 256
    Winsock.gethostname(buf, 256)
    buf.strip
  end
  
  #--------------------------------------------------------------------------
  # ● Returns information about the given service.
  #--------------------------------------------------------------------------
  def self.getservbyname(name)
    case name
    when /echo/i
      return 7
    when /daytime/i
      return 13
    when /ftp/i
      return 21
    when /telnet/i
      return 23
    when /smtp/i
      return 25
    when /time/i
      return 37
    when /http/i
      return 80
    when /pop/i
      return 110
    else
      raise "Service not recognized."
    end
  end
  
  #--------------------------------------------------------------------------
  # ● Creates an INET-sockaddr struct.
  #--------------------------------------------------------------------------  
  def self.sockaddr_in(port, host)
    return - 1 if (host_get = gethostbyname(host)) == -1
    [AF_INET, getservice(port)].pack("sn") + host_get[3] + [].pack("x8")
  end


  #--------------------------------------------------------------------------
  # ● Creates a new socket and connects it to the given host and port.
  #--------------------------------------------------------------------------  
  def self.open(*args)
    socket = new(*args)
    if block_given?
      begin
        yield socket
      ensure
        socket.close
      end
    end
    nil
  end


  #--------------------------------------------------------------------------
  # ● Creates a new socket.
  #--------------------------------------------------------------------------  
  def initialize(domain, type, protocol)
    return SocketError.check if (@fd = Winsock.socket(domain, type, protocol)) == -1
    @fd
  end


  #--------------------------------------------------------------------------
  # ● Accepts incoming connections.
  #--------------------------------------------------------------------------  
  def accept(flags = 0)
    buf = "\0" * 16
    return SocketError.check if Winsock.accept(@fd, buf, flags) == -1
    buf
  end


  #--------------------------------------------------------------------------
  # ● Binds a socket to the given sockaddr.
  #--------------------------------------------------------------------------  
  def bind(sockaddr)
    return SocketError.check if (ret = Winsock.bind(@fd, sockaddr, sockaddr.size)) == -1
    ret
  end


  #--------------------------------------------------------------------------
  # ● Closes a socket.
  #--------------------------------------------------------------------------  
  def close
    return SocketError.check if (ret = Winsock.closesocket(@fd)) == -1
    ret
  end


  #--------------------------------------------------------------------------
  # ● Connects a socket to the given sockaddr.
  #--------------------------------------------------------------------------  
  def connect(sockaddr)
    begin
      return SocketError.check if (ret = Winsock.connect(@fd, sockaddr, sockaddr.size)) == -1
    rescue
      return ret
    ensure


    end
    ret
  end


  #--------------------------------------------------------------------------
  # ● Listens for incoming connections.
  #--------------------------------------------------------------------------  
  def listen(backlog)
    return SocketError.check if (ret = Winsock.listen(@fd, backlog)) == -1
    ret
  end
  
  #--------------------------------------------------------------------------
  # ● Checks waiting data's status.
  #--------------------------------------------------------------------------  
  def select(timeout)
    return SocketError.check if (ret = Winsock.select(1, [1, @fd].pack("ll"), 0, 0, [timeout, timeout * 1000000].pack("ll"))) == -1
    ret
  end
  
  #--------------------------------------------------------------------------
  # ● Checks if data is waiting.
  #--------------------------------------------------------------------------  
  def ready?
    not select(0) == 0
  end  


  #--------------------------------------------------------------------------
  # ● Reads data from socket.
  #--------------------------------------------------------------------------  
  def read(len)
    buf = "\0" * len
    Win32API.new("msvcrt", "_read", "lpl", "l").call(@fd, buf, len)
    buf
  end
  
  #--------------------------------------------------------------------------
  # ● Returns recieved data.
  #--------------------------------------------------------------------------  
  def recv(len, flags = 0)
    buf = "\0" * len
    return SocketError.check if Winsock.recv(@fd, buf, buf.size, flags) == -1
    buf
  end
  
  #--------------------------------------------------------------------------
  # ● Sends data to a host.
  #--------------------------------------------------------------------------  
  def send(data, flags = 0)
    data = data + "\n"
    $socket_tps_action = Time.new.to_f * 1000
    return SocketError.check if (ret = Winsock.send(@fd, data, data.size, flags)) == -1
    ret
  end
  
  #--------------------------------------------------------------------------
  # ● Writes data to socket.
  #--------------------------------------------------------------------------  
  def write(data)
    Win32API.new("msvcrt", "_write", "lpl", "l").call(@fd, data, 1)
  end


  #--------------------------------------------------------------------------
  # ● Set Timeout.
  #--------------------------------------------------------------------------  
  def setTimeout(nbMs)
    buf = [nbMs, nbMs * 1000].pack("ll") 
    return SocketError.check if (ret = Winsock.setsockopt(@fd, SOL_SOCKET, SO_RCVTIMEO, buf, buf.size)) == -1
    ret
  end
  
end


#==============================================================================
# ■ TCPSocket
#------------------------------------------------------------------------------
#  Creates and manages TCP sockets.
#==============================================================================


class TCPSocket < Socket


  #--------------------------------------------------------------------------
  # ● Creates a new socket and connects it to the given host and port.
  #--------------------------------------------------------------------------  
  def self.open(*args)
    socket = new(*args)
    if block_given?
      begin
        yield socket
      ensure
        socket.close
      end
    end
    nil
  end


  #--------------------------------------------------------------------------
  # ● Creates a new socket and connects it to the given host and port.
  #--------------------------------------------------------------------------  
  def initialize(host, port)
    return -1 if super(AF_INET, SOCK_STREAM, IPPROTO_TCP) == -1
    return -1 if setTimeout(6000) == -1
    return -1 if connect(Socket.sockaddr_in(port, host)) == -1
  end
  
 
end


#==============================================================================
# ■ SocketError
#------------------------------------------------------------------------------
#  Default exception class for sockets.
#==============================================================================


class SocketError #< StandardError
  
  #ENOASSOCHOST = "getaddrinfo: no address associated with hostname."
  
  def self.check
    $code_erreur_network = 0
    errno = Winsock.WSAGetLastError
    #print Errno.const_get(Errno.constants.detect { |c| Errno.const_get(c).new.errno == errno })
    erreur = Errno.const_get(Errno.constants.detect { |c| Errno.const_get(c).new.errno == errno })
    $code_erreur_network = errno
    $fic_log.write("Erreur : #{errno} : #{erreur}\n" )
    return -1
    
  end
  
end



network *
Spoiler
#==============================================================================
# ■ Class Network
#------------------------------------------------------------------------------
# Script permettant la gestion du socket optimisé pour mode multijoueur léger
#   avec gestion d'un serveur externe
# Date : 20/07/2006
#   Version   Date          Auteur        Commentaires
#   1.05      07/01/2007    Tonyryu       Optimisation du code
#   1.06      19/02/2007    Tonyryu       Gestion du serveur introuvable
#   1.07      14/07/2007    Tonyryu       Modification gestion d'erreur
#   1.08      19/07/2007    Tonyryu       optimisation des retours de fonctions
#
#==============================================================================


class Network
  
  #--------------------------------------------------------------------------
  # ● Constantes
  #--------------------------------------------------------------------------   
  
  # Erreurs
  $NET_ERR            = -1
  $NET_ERR_DELAIS     = -1
  $NET_ERR_CONNECT    = -2
  
  # Login
  $NET_LOG_NOK        = 0
  $NET_LOG_OK         = 1
  $NET_LOG_UTILISE    = 2
  
  # Version
  $NET_VER_NOK        = 0
  $NET_VER_OK         = 1
  
  
  # Tps d'attente ms
  $NET_TPS_DECO       = 3000
  $NET_TPS_TEST       = 6000
  
  # Fichier de log
  $fic_log = File.new("log.txt", "w")
  $fic_log.write("Log\n\n")
  $portServeur = 3100
  
  
  #--------------------------------------------------------------------------
  # ● Attributs
  #--------------------------------------------------------------------------   
  attr_reader   :socket
  attr_reader   :tabMessages
  attr_accessor :bNouveauMessage
  attr_accessor :besoinMaj
  
  
  #--------------------------------------------------------------------------
  # ● Initialize
  #-------------------------------------------------------------------------- 
  def initialize
    
    # Données liés au socket
    $code_erreur_network = 0
    @bCanalOuvert = false
    @bTpsAttenteDepasse = false
    @reponse = ""
    @finConnect = false
    #@attente_reponse = false
    
    
    # Données du tchat
    @nbreMessageMaxi = 40
    $tabMessages = []
    @bNouveauMessage = false
    
    # Données du transfert de fichier
    $ftp_etat = "INIT"
    $ftp_pourcentage = 0
    
    # Données spécifique au projet
    $nbJoueur = 0
    
    
  end
  # ● Entrer l'adresse Ip de l'ami
  def adresse_Ip
      int = Interpreter.new
    $IP = int.password("Entrez l'adresse IP :",12)
    end
  #--------------------------------------------------------------------------
  # ● demarrer
  # param : adrServeur : adresse [:port] du serveur
  #--------------------------------------------------------------------------
  def demarrer_socket(adrServeur)
    # Réinitialiser
    initialize
    
    # Se connecter au serveur
    begin
      $fic_log.write("\nOuverture du socket : ")
      if ouvrirSocket(adrServeur)
        $fic_log.write("OK\n")
        @bCanalOuvert = true
      else
        $fic_log.write("Erreur\n")
      end
    end
    if !@bCanalOuvert
      fermer_socket
      return false 
    end
    
    # Initialiser le timer d'activité
    $socket_tps_action = Time.new.to_f * 1000
    
    demarrerLectureContinue
    sleep(0.01)
    return true
  end
    
  #--------------------------------------------------------------------------
  # ● ouvrirSocket
  #--------------------------------------------------------------------------
  def ouvrirSocket(adrServeur)
    portServeur = $portServeur
    # Vérifier si l'adresse ne contient pas un port de renseigner
    port = adrServeur.slice!(/ :( .*)/)
    if port != nil
      port[':'] = ''
      portServeur = port
    end
    @socket = TCPSocket.new(adrServeur, portServeur.to_i)
    return true if $code_erreur_network == 0
    return false
  end
  
  #--------------------------------------------------------------------------
  # ● canalOuvert?
  #--------------------------------------------------------------------------
  def canalOuvert?
    return @bCanalOuvert
  end


  #--------------------------------------------------------------------------
  # ● erreurNetwork?
  #--------------------------------------------------------------------------
  def erreurNetwork?
    return ($code_erreur_network != 0)
  end


  #--------------------------------------------------------------------------
  # ● fermer_socket
  #--------------------------------------------------------------------------
  def fermer_socket(bThread = false)
    sleep(0.2)
    @bCanalOuvert = false
    if !bThread
      arreterLectureContinue
    end
    @socket.close if !@socket.nil?
    @socket = nil
  end  
  
  #--------------------------------------------------------------------------
  # ● gerer_erreur
  #--------------------------------------------------------------------------
  def gerer_erreur(bThread = false)
    # Si une erreur s'est produis sur le socket
    if $code_erreur_network != 0 or @bTpsAttenteDepasse
      fermer_socket(bThread)
      $code_erreur_network = -1
      return false
    end


    return true
  end
  
  #--------------------------------------------------------------------------
  # ● envoyer
  #--------------------------------------------------------------------------
  def envoyer(trame)
    $fic_log.write("Envoie : #{trame}\n") if trame != "T"
    @socket.send(trame) if $code_erreur_network == 0
    return gerer_erreur
  end
  
  #--------------------------------------------------------------------------
  # ● envoyer_et_attendre
  #--------------------------------------------------------------------------
  def envoyer_et_attendre(trame)
    # Vérifier l'etat du socket
    if @bCanalOuvert
      
      # Utiliser une variable temporaire pour compter le temps
      varTps = 0
      # Vider la variable réponse
      @reponse = ""
      # Récupérer la valeur du timer
      latence = Time.new.to_f * 1000
      # Envoyer la trame au serveur
      
      # Gérer les erreurs éventuels
      if envoyer(trame)
      
        # Tant que pas de réponse et le canal est ouvert
        while  @reponse == "" and @bCanalOuvert
          
          # Si le temps d'attente est dépassé
          if varTps > $NET_TPS_DECO
            # gerer les erreurs sur un timeout
            @bTpsAttenteDepasse = true
            $fic_log.write("\nErreur : Temps d'attente de réponse dépassé\n")
            gerer_erreur
            return  false
          end
          
          # Attendre 10ms
          sleep(0.01)
          varTps += 10
        end
        # Calculer le temps entre requete/réponse
        latence = (Time.new.to_f * 1000) - latence
        $fic_log.write("latence réponse : #{latence.to_i} ms\n\n")
        
        # Renvoyer vrai
        return true
        
      end
    end
    return false
  end
  
  #--------------------------------------------------------------------------
  # ● reponse
  #-------------------------------------------------------------------------- 
  def reponse
    return @reponse
  end
  
  #--------------------------------------------------------------------------
  # ● demarrerLectureContinue
  #-------------------------------------------------------------------------- 
  def demarrerLectureContinue
    # Gérer les erreurs dans les thread
    Thread.abort_on_exception = true
    # Démarrer la lecture continue
    @th_lecture = Thread.new { lecture_continue }
  end
    
  #--------------------------------------------------------------------------
  # ● arreterLectureContinue
  #-------------------------------------------------------------------------- 
  def arreterLectureContinue
    if !@th_lecture.nil?
      @th_lecture.exit
      @th_lecture = nil
    end
    $fic_log.write("\nArret de la lecture continue\n")
  end
  
  #--------------------------------------------------------------------------
  # ● lecture_continue
  #-------------------------------------------------------------------------- 
  def lecture_continue
    $fic_log.write("\nDémarrage Lecture continue\n")
    loop do
      # lire une trame du socket
      trame = lire


      # Si une erreur s'est produis 
      if trame == "-1"
        # Gestion des erreurs
        break if !gerer_erreur(true)
      end
      
      # Si la trame contient une information a traiter
      if trame != ""
        gerer_trame(trame)
      end
      
      # Si socket inactif depuis temps test, alors tester la connection
      if ((Time.new.to_f * 1000) - $socket_tps_action) > $NET_TPS_TEST
        # Envoyer T
        @socket.send("T")
        
        # Gestion des erreurs
        break if !gerer_erreur(true)
          
      end


      # Attendre 1 ms
      sleep(0.001)
    end
    $fic_log.write("\nlecture_continue cassée\n")
    
  rescue => erreur
    $fic_log.write( "Erreur :\n" + erreur.message + erreur.backtrace.join("\n") + "\n")


  end 
  
  #--------------------------------------------------------------------------
  # ● lire
  #-------------------------------------------------------------------------- 
  def lire
    
    # Initialisation des variables
    trame = ""
    cara = ""
    taille = []
    # Si le socket est prêt
    if @socket.ready?
      # Prendre un caractére sur le socket
      cara = @socket.recv(0x01)
      # Si une erreur s'est produite
      if $code_erreur_network != 0
        # Ecrire un erreur dans le fichier de log
        $fic_log.write("\nErreur : Lecture d'un octet dans le socket\n")
        # Retourner le code erreur -1
        return "-1"
      end
      
      if cara == "0"
        # Récupérer la taille de la trame sur le socket
        taille = @socket.recv(0x04).to_i
        # Si une erreur s'est produite
        if $code_erreur_network != 0
          # Ecrire un erreur dans le fichier de log
          $fic_log.write("\nErreur : Lecture de la taille de trame dans le socket\n")
          # Retourner le code erreur -1
          return "-1"
        end
        
        # Lire la trame sur le socket
        trame =  @socket.recv(taille)
        # Informer que le socket a subit une action a cet instant
        $socket_tps_action = Time.new.to_f * 1000
        # Si une erreur s'est produite
        if $code_erreur_network != 0
          $fic_log.write("\nErreur : Lecture de la trame dans le socket\n")
          # Retourner le code erreur -1
          return "-1"
        end
        # indiquer dans le fichier de log les trames reçu
        $fic_log.write("\nreçu : #{trame}\n")
        #$fic_log.write("octet : #{trame.size + 5}\n")
      end
      
    # Si une erreur s'est produite
    elsif $code_erreur_network != 0
      # Ecrire un erreur dans le fichier de log
      $fic_log.write("\nErreur lors de la vérification de disponibilité du socket\n")
      # Retourner le code erreur -1
      return "-1"
    end
    return trame


  end


  #-------------------------------------------------------------------------- 
  # ● recevoir_fichier.
  #-------------------------------------------------------------------------- 
  def recevoirFichier(nomFic)
    @th_reception = Thread.new { thRecevoirFichier(nomFic) }
  end
  
  #-------------------------------------------------------------------------- 
  # ● thRecevoirFichier.
  #-------------------------------------------------------------------------- 
  def thRecevoirFichier(nomFic)


    # Initialiser les variables     
    enteteTrame = ""
    bErreurTransfert = false
    trame = ""
    
    lectureContinu = false
    $ftp_octetRecu = 0
    nbTrame = 0
    
    # Variable Globale d'état (déjà définit dans l'initialisation de la classe Network)
    $ftp_etat = "ENCOURS"
    $fic_log.write("\nRéception du fichier : [#{nomFic}]\n")
  
    # Arreter la lecture continue si activé
    if !@th_lecture.nil?
      lectureContinu = true
      arreterLectureContinue
    end
    
    sleep(2)
    # Demander au serveur d'envoyer le fichier voulu
    envoyer("ENVFIC:#{nomFic}")
    
    # Tant que le fichier n'est pas terminé
    while $ftp_etat == "ENCOURS" # and !bErreurTransfert and $code_erreur_network == 0
      
      # Récupérer la trame réseau
      trame = lire
      
      # Gerer les erreur
      if !gerer_erreur
        # Modifier la variable Globale d'état
        $ftp_etat = "ERREUR"
        $fic_log.write("Erreur de transfert : Problème de lecture de trame\n")
      end


      # Récupérer l'entête de la trame sur 9 caractères
      enteteTrame = trame[0,9]
      #$fic_log.write("enteteTrame : #{enteteTrame}\n")
      
      # Selon l'entête      
      case enteteTrame
      when "FINCONNU-"
        $ftp_etat = "INCONNU"
        $fic_log.write("Fichier non connu du serveur\n")
      
      when "FTAILLE--"
        # Récupération de la taille du fichier, sur 9 caractères
        $ftp_octetFic = trame[9, 9].to_i
        nbOctetTrame = trame[18, 9].to_i
        $fic_log.write("Taille du fichier : #{$ftp_octetFic} octets, divisé par trame de #{nbOctetTrame} octets\n")
        
        # Calculer le nombre de trame de données à réceptionné
        nbTrame = $ftp_octetFic / nbOctetTrame
        nbTrame += 1 if $ftp_octetFic % nbOctetTrame != 0
        
        # Dimensionné le tableau de données
        tabTrame = {}
        
      when "FTRAME---"
        # Récupération du numéro de la trame, sur 9 caractères
        numTrame = trame[9, 9].to_i
        #$fic_log.write("Numéro de trame : #{numTrame}\n")
        
        # Vérifier que l'on a bien une taille de fichier a recevoir
        if $ftp_octetFic == 0
          # Générer une erreur
          $ftp_etat = "ERREUR"
          envoyer("FTRAME:NOK")
          $fic_log.write("Erreur de transfert : taille de fichier\n")
          # quitter
          return "-1"
        end
        
        #tabTrame.push(trame[18, trame.size - 18])
        tabTrame[numTrame-1] = trame[18, trame.size - 18]
        $ftp_octetRecu += trame.size - 18
        
        #envoyer("FTRAME:OK")
        
        $ftp_etat = "CHARGE" if $ftp_octetRecu == $ftp_octetFic
        sleep(0.003)


      end


    end
    
    if $ftp_etat == "CHARGE"
      
      $fic_log.write("Restructuration\n")
      #@octetFichierRecu += $ftp_octetRecu
      
      fic = File.new(nomFic, "wb")
      for i in 0...tabTrame.size
        fic.write(tabTrame)
      end
      fic.close
      $fic_log.write("Fichier téléchargé\n")
      $ftp_etat = "TERMINE"
    end
    
    # Remettre en route la lecture continue si elle était active
    if lectureContinu == true
      demarrerLectureContinue
    end
    
  rescue => erreur
    $fic_log.write( "Erreur :\n" + erreur.message + erreur.backtrace.join("\n") + "\n")




  end


  
end




Network cmd
Spoiler
class Network


  #--------------------------------------------------------------------------
  # ● gerer_trame
  #-------------------------------------------------------------------------- 
  def gerer_trame(trame = "")
    
    case trame
    #
    when /START:(.*)/
      return reponce = $1
    # 
    when  /ECHANGE:(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)&(.*)/
    $id_recep = $1
    $shiny_recep = $2
    $Hp_recep = $3
    $Hp_Max_recep = $4
    $atk_recep = $5
    $dfe_recep =  $6
    $ats_recep = $7
    $dfs_recep = $8
    $spd_recep =  $9
    $exp_recep = $10
    $next_exp_recep = $11
    $nature_recep = $12
    $combat_recep =  $13
    $name_dresseur_recep = $14
    $id_dresseur_recep = $15
    $item_name_recep = $16
    $type_ball_recep = $17
    $sexe_recep = $18
    $nom_recep = $19
    $level_recep = $20
    $game_switches[14] = true


    else
      
    end
    
  end
  
end




Echange
Spoiler
#==============================================================================  
# ■ Echange
  
# 28/07/10 -  par Titi6 
#-----------------------------------------------------------------------------  
# Scène modifiable mais attention a vos risque est péril lol Clin d'œil foireux
#-----------------------------------------------------------------------------  
# Systeme d'échange en temps réel
#-----------------------------------------------------------------------------  


class Echange
  
  $nom_att = [nil]
  $pp = [nil]
  $pp_max = [nil]
  
  def PKMN_Echange(pokemon)
   #On récupert tout sur le pokémon à échanger
  $id = pokemon.id.to_s
  $nom = pokemon.name.to_s
  $level = pokemon.level.to_s
  $shiny  = pokemon.shiny ? 1 : 0.to_s
  $Hp = pokemon.hp.to_s
  $Hp_Max = pokemon.maxhp_basis.to_s
  $atk = pokemon.atk.to_s
  $dfe =  pokemon.dfe.to_s
  $ats = pokemon.ats.to_s
  $dfs = pokemon.dfs.to_s
  $spd =  pokemon.spd.to_s
  $exp = pokemon.exp.to_s
  $next_exp = pokemon.next_exp.to_s
  $nature = pokemon.nature.to_s
  $combat =  pokemon.fight.to_s
  $name_dresseur = pokemon.trainer_name.to_s
  $id_dresseur = pokemon.trainer_id.to_s
  $item_name = pokemon.item_name.to_s
  $type_ball = pokemon.ball_sprite.to_s
  $sexe = pokemon.gender.to_s
  i = 0
  for skill in pokemon.skills_set
  $nom_att = skill.name
  $pp = skill.pp
  $pp_max = skill.ppmax
   i += 1
 end
 trame= "ECHANGE:"+$id+"&"+$shiny+"&"+$Hp+"&"+$Hp_Max+"&"+$atk+"&"+$dfe
 trame = trame+"&"+$ats+"&"+$dfs+"&"+$spd+"&"+$exp+"&"+$next_exp
 trame = trame+"&"+$nature+"&"+$combat+"&"+$name_dresseur+"&"+$id_dresseur
 trame = trame+"&"+$item_name+"&"+$type_ball+"&"+$sexe+"&"+$nom+"&"+$level
  $network.envoyer(trame)
end
end




Scene_Ip
Spoiler
#==============================================================================
# ■ Scene_Password
#------------------------------------------------------------------------------
#  名前入力画面の処理を行うクラスです。
#==============================================================================


class Scene_Ip
  #--------------------------------------------------------------------------
  # ● メイン処理
  #--------------------------------------------------------------------------
  def main(texte)
    Graphics.freeze
    @z_level = 10000
    @background = Sprite.new
    string_dp = $game_variables[5000]["menu_dp"] ? "_DP" : ""
    @background.bitmap = RPG::Cache.picture("name" + string_dp + ".png")
    @background.z = @z_level
    
    @edit_window = Window_IpEdit.new($game_temp.name_max_char,texte)
    @input_window = Window_Ip.new
    
    @edit_window.z = @z_level + 1
    @input_window.z = @z_level + 2
    
    @done = false
    Graphics.transition
    loop do
      Graphics.update
      Input.update
      update
      if @done
        break
      end
    end
    Graphics.freeze
    @edit_window.dispose
    @input_window.dispose
    @background.dispose
  end
  #--------------------------------------------------------------------------
  # ● フレーム更新
  #--------------------------------------------------------------------------
  def update
    @edit_window.update
    @input_window.update
    # Effacement
    if Input.repeat?(Input::B)
      if @edit_window.index == 0
        return
      end
      $game_system.se_play($data_system.cancel_se)
      @edit_window.back
      return
    end
    
    # Confirmer
    if Input.trigger?(Input::C)
      # Bouton sur Confirmer
      if @input_window.character == nil
        # Pas de nom entrée => Par défaut
        if @edit_window.name == ""
          @edit_window.restore_default
          if @edit_window.name == ""
            $game_system.se_play($data_system.buzzer_se)
            @done = true
            return
          end
          $game_system.se_play($data_system.decision_se)
          return
        end
        $game_system.se_play($data_system.decision_se)
        
        $password = @edit_window.name
        @done = true
        return
      end
      
      # Entrée d'un caractère de trop
      if @edit_window.index == $game_temp.name_max_char
        $game_system.se_play($data_system.buzzer_se)
        return
      end


      # Entrée d'un mauvais caractère
      if @input_window.character == ""
        $game_system.se_play($data_system.buzzer_se)
        return
      end
      
      $game_system.se_play($data_system.decision_se)
      
      @edit_window.add(@input_window.character)
      return
    end
  end
end



Window_Ip
Spoiler
#==============================================================================
# ■ Window_PasswordInput
# Pokemon Script Project - Krosk 
# 19/08/07
#-----------------------------------------------------------------------------
# Scène à ne pas modifier
#-----------------------------------------------------------------------------


  class Window_Ip < Window_Base
    CHARACTER_TABLE =
    [
     "0","1","2","3","4",
     "5","6","7","8","9",
     ".","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     
    "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","",""
    ]
    
    CHARACTER_TABLE_EX =
    [
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","","",
     "","","","",""
    ]
    #--------------------------------------------------------------------------
    # ? ?????????
    #--------------------------------------------------------------------------
    def initialize(ex_table = false)
      super(30, 150, 555, 300)
      self.contents = Bitmap.new(width - 32, height - 32)
      self.contents.font.name = $fontface
      self.contents.font.size = $fontsize
      self.contents.font.color = normal_color
      self.opacity = 0
      @index = 0
      @ex_table = ex_table
      refresh
      update_cursor_rect
    end
    #--------------------------------------------------------------------------
    # ? ??????
    #--------------------------------------------------------------------------
    def refresh
      self.contents.clear
      for i in 0..134
        x = 24 + i / 5 / 9 * 152 + i % 5 * 28
        y = 9 + i / 5 % 9 * 29
        if @ex_table
          self.contents.draw_text(x, y, 28, 32, CHARACTER_TABLE_EX, 1)
        else
          self.contents.draw_text(x, y, 28, 32, CHARACTER_TABLE, 1)
        end
      end
      self.contents.draw_text(0, 9 + 8 * 29, 511, 32, "OK", 2)
    end  
    
    #--------------------------------------------------------------------------
    # ? ?????
    #--------------------------------------------------------------------------
    def character
      if @ex_table
        return CHARACTER_TABLE_EX[@index]
      end
      return CHARACTER_TABLE[@index]
    end
    #--------------------------------------------------------------------------
    # ? ?????????
    #--------------------------------------------------------------------------
    def update_cursor_rect
      # ??????? [??] ???
      if @index >= 135
        self.cursor_rect.set(483, 9 + 8 * 29, 32, 32)
      # ??????? [??] ?????
      else
        x = 24 + @index / 5 / 9 * 152 + @index % 5 * 28
        y = 9 + @index / 5 % 9 * 29
        self.cursor_rect.set(x, y, 32, 32)
      end
    end
    #--------------------------------------------------------------------------
    # ? ??????
    #--------------------------------------------------------------------------
    def update
      super
      # ??????? [??] ???
      if @index >= 135
        @index = 135
        # ?????
        if Input.trigger?(Input::LEFT)
          $game_system.se_play($data_system.cursor_se)
          @index = 134
        end
        # ?????
        if Input.trigger?(Input::RIGHT)
          $game_system.se_play($data_system.cursor_se)
          @index = 40
        end
      # ??????? [??] ?????
      else
        # ??????????????
        if Input.repeat?(Input::RIGHT)
          # ????????????????
          # ???????????????
          if Input.trigger?(Input::RIGHT) or
             @index / 45 < 2 or @index % 5 < 4
            # ?????????
            $game_system.se_play($data_system.cursor_se)
            if @index % 5 < 4
              @index += 1
            else
              @index += 45 - 4
            end
            if @index >= 135
              @index -= 135
            end
            if @index == 40
              @index = 135
            end
          end
        end
        # ??????????????
        if Input.repeat?(Input::LEFT)
          # ????????????????
          # ???????????????
          if Input.trigger?(Input::LEFT) or
             @index / 45 > 0 or @index % 5 > 0
            # ?????????
            $game_system.se_play($data_system.cursor_se)
            if @index % 5 > 0
              @index -= 1
            else
              @index -= 45 - 4
            end
            if @index < 0
              @index += 135
            end
            if @index == 134
              @index = 135
            end
          end
        end
        # ??????????????
        if Input.repeat?(Input::DOWN)
          # ?????????
          if Input.trigger?(Input::DOWN) or @index % 45 < 40
            $game_system.se_play($data_system.cursor_se)
            if @index % 45 < 40
              @index += 5
            else
              @index -= 40
            end
          end
        end
        # ??????????????
        if Input.repeat?(Input::UP)
          # ????????????????
          # ???????????????
          if Input.trigger?(Input::UP) or @index % 45 >= 5
            # ?????????
            $game_system.se_play($data_system.cursor_se)
            if @index % 45 >= 5
              @index -= 5
            else
              @index += 40
            end
          end
        end
        # L ???? R ??????????
        if Input.repeat?(Input::L) or Input.repeat?(Input::R)
          # ???? / ???? ??
          $game_system.se_play($data_system.cursor_se)
          if @index / 45 < 2
            @index += 90
          else
            @index -= 90
          end
        end
      end
      update_cursor_rect
    end
  end




Window_IpEdit
Spoiler
#==============================================================================
# ■ Window_PasswordEdit
# Pokemon Script Project - Krosk 
# 19/08/07
#-----------------------------------------------------------------------------
# Scène à ne pas modifier
#-----------------------------------------------------------------------------


class Window_IpEdit < Window_Base
  attr_accessor :name                     # 名前
  attr_accessor :index                    # カーソル位置
  #--------------------------------------------------------------------------
  # ● オブジェクト初期化
  #--------------------------------------------------------------------------
  def initialize(max_char,texte)
    super(99, 27, 442, 114)
    self.contents = Bitmap.new(width - 32, height - 32)
    self.contents.font.name = $fontface
    self.contents.font.size = $fontsizebig
    self.contents.font.color = normal_color
    self.opacity = 0
    $password = ""
    @name = ""
    @max_char = max_char
    @texte = texte
    name_array = @name.split(//)[0...@max_char]
    @name = ""
    for i in 0...name_array.size
      @name += name_array
    end
    @default_name = @name
    @index = name_array.size
    refresh
    update_cursor_rect
  end
  #--------------------------------------------------------------------------
  # ● リフレッシュ
  #--------------------------------------------------------------------------
  def refresh
    self.contents.clear
    
    name_array = @name.split(//)
    for i in 0...@max_char
      c = name_array
      if c == nil
        c = "_"
      end
      x = 203.5 - (@max_char * 10.5) + (i * 21)
      draw_text(x, 33, 24, 44, c, 1, normal_color)
    end
    
    self.contents.font.size = $fontsize
    
    self.contents.draw_text(0, 0, 410, $fontsizebig, @texte, 1)
    self.contents.font.size = $fontsizebig
  end
  #--------------------------------------------------------------------------
  # ● カーソルの矩形更新
  #--------------------------------------------------------------------------
  def update_cursor_rect
    x = 196.5 - (@max_char * 10.5) + (@index * 21)
    if @index == @max_char
      x -= 21
    end
    self.cursor_rect.set(x, 40, 32, 32)
  end
  def back
    if @index > 0
      # 一字削除
      name_array = @name.split(//)
      @name = ""
      for i in 0...name_array.size-1
        @name += name_array
      end
      @index -= 1
      refresh
      update_cursor_rect
    end
  end
  def add(character)
    if @index < @max_char and character != ""
      @name += character
      @index += 1
      refresh
      update_cursor_rect
    end
  end
  def restore_default
    @name = @default_name
    @index = @name.split(//).size
    refresh
    update_cursor_rect
  end
end




Voilà pour les scripts


Le serveur est en ruby il faut donc avoir ruby sur son ordinateur (google is your friend)
Le serveur à télécharger ici


puis 2 petits évènement 


Pour l'envoie du PKMN
Spoiler




Pour <<recevoir>> (marche pas enfin plus ou moin ^^)
Spoiler





La demo pour finir
ICI

Posté par Titi6 le 20 Sep - 17:32 (2010)
Il n'y a pas personne pour me dire comment elle marche cette fonction?bon voilà mon code 
 
Code:
 ajouter_pokemon_param("ID" => $id_recep, "NV" => $level_recep)




Mais sa marche pas  :(

svp je mettrai a disposition mon code après l'avoir terminer en plus tout le monde pourra en profiter

Posté par Titi6 le 30 Sep - 19:41 (2010)
toujours personne pour m'aider?

Posté par Pαlвσlѕку le 30 Sep - 20:21 (2010)
Je ne vois pas ce qui cloche...

Tu peux m'envoyer ton code par MP ? Ca pourrait m'aider pour savoir pourquoi ça ne fonctionne pas.

Posté par Nuri Yuri le 30 Sep - 21:03 (2010)
Code:
ajouter_pokemon_param({"ID" => $id_recep, "NV" => $level_recep})

Ça devrais marcher ...

Posté par Sphinx le 30 Sep - 23:07 (2010)
En effet, l'argument (parce que cette fonction ne prend qu'une seule structure de données, comme argument =)) est une table de hachage (ou hash pour faire plus court), et toute hash doit être encadrée d'accolades.

Bref, Youri a donné la solution, qui, je crois, devrait se trouver également dans le manuel de PSP0.7 =)

Ceci dit, je suis impressionné par le rendu ^o^ Les scripts sont de toi ?

Posté par Titi6 le 2 Oct - 09:30 (2010)
Merci de m'avoir répondue  :lol:


Bon alors voilà sa marche toujours pas  :( . j'ai l'erreur suivant





voici mon code que j'ai rajouter

Spoiler





Les scripts ne sont pas de moi mais de Denis Bros (cf 1° message) mais j'ai adapté les scripts pour PSP4G+ donc il sont 50% moi et 50% Denis


Pαlвσlѕку pour le code ben y a que cette évènement qui bug sinon tout le reste marche nickel


merci de votre aide à tous

Posté par Titi6 le 8 Oct - 07:57 (2010)
Mise à jours du poste Voilà les script et la demo bonne chance à celui qui arrivera à développer 

Posté par Titi6 le 18 Oct - 19:40 (2010)
Salut,


Personne n'a donc trouver de solution pour mon script? Si vous la trouver merci de faire profiter les autres comme j'ai fait


Bon jeu a tous

Posté par Sphinx le 18 Oct - 20:19 (2010)
^o^" Je ne sais pas trop quelle aide tu souhaitais, mais apparemment ta démo, c'est un lien mort xD