Partage
  • Partager sur Facebook
  • Partager sur Twitter

Comment utiliser le TCP pour envoyer des fichiers

    18 mai 2018 à 15:27:26

    Bonjour,

    Je fais un programme qui permet à un hôte d'héberger un fichier et à un client de télécharger le fichier proposé par l'hôte (en TCP)

    Le programme marche, seulement lorsque le client écrit le fichier, le fichier produit fait 3 à 4 fois la taille de celui de base, et est inutilisable.

    Coté client:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Peerload.Network {
    
        class Client : INetSide{
    
            readonly String TargettedIP, WhereSaveFile, Port;
    
            public Client(String TargettedIP, String WhereSaveFile, String Port) {
                this.TargettedIP = TargettedIP;
                this.WhereSaveFile = WhereSaveFile;
                this.Port = Port;
                Task t = Task.Factory.StartNew(() => Run());
            }
    
            public void Run() {
                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(TargettedIP, Int32.Parse(Port));
                NetworkStream stream = tcpClient.GetStream();
                BinaryWriter writer = new BinaryWriter(new FileStream(WhereSaveFile, FileMode.Create));
                int currentByte;
                while ((currentByte = stream.ReadByte()) != -1) writer.Write(currentByte);
            }
    
            public void Destroy() {
    
            }
    
            public String GetIP() {
                return TargettedIP;
            }
    
        }
    }
    

    Coté serveur:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;
    
    namespace Peerload.Network {
    
        class Server : INetSide {
    
            /* Fields */
            private readonly String file;
            private readonly int ServerPort;
            private readonly String ServerIP;
            private readonly TcpListener ServerSocket;
            private readonly Task ServerTask;
            private readonly CancellationTokenSource TaskCancellation;
            private readonly CancellationToken Token;
            private readonly byte[] buffer;
            /* Constructor */
            public Server(String file, int port) {
                
                /* Initialize fields */
                this.file = file;
                this.ServerPort = port;
                this.ServerIP = "http://localhost:" + ServerPort + "/Peerload";
                this.ServerSocket = new TcpListener(ServerPort);
                this.buffer = File.ReadAllBytes(file);
                this.TaskCancellation = new CancellationTokenSource();
                this.Token = TaskCancellation.Token;
                this.ServerTask = Task.Factory.StartNew(() => Run(), Token);
                Program.GetMainForm().DebugConsole.Text += "\nServer now accepts TCP connections";
            }
    
    
            /* Getter for the file downloadable from this instance of server */
            public String ServerFile {
                get {
                    return this.file;
                }
            }
            Boolean stop = false;
            /* Make running the server */
            public void Run() {
                ServerSocket.Start();
    
                while (!stop) {
                    TcpClient ClientSocket = ServerSocket.AcceptTcpClient();
                    NetworkStream ClientStream = ClientSocket.GetStream();
                    ClientStream.Write(this.buffer, 0, this.buffer.Length);
                    ClientStream.Flush();
    
    
                }
            }
            
            /* Destroy the server, it will not be accessible after that */
            public void Destroy() {
                stop = true;
                ServerTask.Wait();
                ServerSocket.Stop();
            }
    
            public String GetIP() {
                return new WebClient().DownloadString("http://icanhazip.com");
            }
    
    
    
        }
    }
    

    Pouvez-vous m'aider ?


    • Partager sur Facebook
    • Partager sur Twitter
    Plus c'est simple moins c'est drôle - Le racisme, c'est bien qu'envers le JS.
      22 juin 2018 à 16:15:03

      TCP est orienté Flux, donc pas message et encore moins fichier.

      Utilisez le protocole FTP ou un de ses dérivés pour transférer des fichiers. Vous galèreriez beaucoup moins.

      Ici, votre code ne fait que remplir le fichier sur le client qu'avec des "0x000000xx" où xx est l'octet lu.

      Vous écrivez un "0x000000xx" par octet lu dans le flux, ce qui explique le *4 du fichier en sortie.

      https://msdn.microsoft.com/fr-fr/library/system.io.stream.read(v=vs.110).aspx

      • Partager sur Facebook
      • Partager sur Twitter
      Je recherche un CDI/CDD/mission freelance comme Architecte Logiciel/ Expert Technique sur technologies Microsoft.

      Comment utiliser le TCP pour envoyer des fichiers

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown