Ver Mensaje Individual
  #1 (permalink)  
Antiguo 31/12/2010, 06:29
Avatar de Nemutagk
Nemutagk
Colaborador
 
Fecha de Ingreso: marzo-2004
Ubicación: México
Mensajes: 2.633
Antigüedad: 21 años
Puntos: 406
Problema con socket y envió de imágenes C#

Que tal compañeros, traigo un problema, estoy comenzando con C# y estoy haciendo pruebas con sockets en programas cliente/servidor, ya logre enviar y recibir archivos, mas especifico en imágenes, pero tengo un problema, al principio se me complico mucho porque al parecer el socket envía el archivo (sea cual sea el tipo) en bloques de x bytes, así que siempre recibía solo una parte del archivo (la prueba la hacia con imágenes, con lo cual solo se veía una parte, lo demás de color gris), logré al final eh digamos compaginar (no encuentro otra forma de decirlo) los bloques de bytes y crear el archivo completo, el problema ahora y de plano llevo bastante buscando y no encuentro la razon es que no me llega el archivo completo, lo que pienso es que no obtengo el peso total en bytes en el cliente (o lo obtengo de forma erronea) o de plano la "solución" que implemente esta mal, ya que siempre falta algunos bytes (no mas de 10 en las pruebas que eh hecho), por ejemplo, al enviar una imagen verifico la ventana de propiedades de windows y me marca un peso de 48,758 bytes, pero en el archivo que obtengo al enviarlo me marca 48,750 bytes, como verán faltan 8 bytes...

Si me pudieran ayudar viendo si lo que hice esta bien o de plano regreso a estudiar mas >.<, aquí dejo el código de los programas...

Cliente (el que envía)
Código c#:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.IO;
  12. using System.Threading;
  13.  
  14. namespace EnvioArchivos
  15. {
  16.     public partial class Form1 : Form
  17.     {
  18.         bool conectado = false;
  19.         Socket socket;
  20.         Thread trabajo;
  21.  
  22.         public Form1()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.  
  27.         delegate void SetTextCallback(string text);
  28.  
  29.         private void button1_Click(object sender, EventArgs e)
  30.         {
  31.             if (!conectado)
  32.             {
  33.                 conectar();
  34.                 conectado = true;
  35.             }
  36.             else
  37.             {
  38.                 byte[] msn = System.Text.Encoding.ASCII.GetBytes("close");
  39.                 socket.Send(msn);
  40.                 desconectar();
  41.             }
  42.         }
  43.  
  44.         private void button2_Click(object sender, EventArgs e)
  45.         {
  46.             if (openFileDialog1.ShowDialog() == DialogResult.OK)
  47.             {
  48.                 enviarArchivo(openFileDialog1.FileName);
  49.             }
  50.         }
  51.  
  52.         private void conectar()
  53.         {
  54.             button1.Text = "Desconectar";
  55.             button2.Enabled = true;
  56.             button3.Enabled = true;
  57.             textBox3.Enabled = true;
  58.  
  59.             IPAddress ipServer = Dns.GetHostEntry(textBox1.Text).AddressList[0];
  60.             IPEndPoint ipEndPoint = new IPEndPoint(ipServer, 1050);
  61.             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  62.  
  63.             try
  64.             {
  65.                 addText("Intentando conectar...");
  66.                 socket.Connect(ipEndPoint);
  67.  
  68.                 ParameterizedThreadStart threadMensajes = new ParameterizedThreadStart(this.checarMensajes);
  69.                 trabajo = new Thread(threadMensajes);
  70.                 trabajo.IsBackground = true;
  71.                 trabajo.Start(socket);
  72.  
  73.                 if (socket.Connected)
  74.                 {
  75.                     addText("Conectado!!!");
  76.                 }
  77.             }
  78.             catch (Exception e)
  79.             {
  80.                 addText("Error al intentar conectar \r\n" + e.ToString());
  81.                 button1.Text = "Conectar";
  82.                 button2.Enabled = false;
  83.                 conectado = false;
  84.             }    
  85.         }
  86.  
  87.         private void desconectar()
  88.         {
  89.             //trabajo.Join();
  90.             trabajo.Suspend();
  91.             socket.Close();
  92.  
  93.             addText("Desconectado");
  94.  
  95.             button1.Text = "Conectar";
  96.             button2.Enabled = false;
  97.             button3.Enabled = false;
  98.             textBox3.Enabled = false;
  99.             conectado = false;
  100.         }
  101.  
  102.         private void enviarArchivo(string NombreFichero)
  103.         {
  104.             string RutaFichero = "";
  105.  
  106.             NombreFichero = NombreFichero.Replace("\\", "/");
  107.             while (NombreFichero.IndexOf("/") > -1)
  108.             {
  109.                 RutaFichero += NombreFichero.Substring(0, NombreFichero.IndexOf("/") + 1);
  110.                 NombreFichero = NombreFichero.Substring(NombreFichero.IndexOf("/") + 1);
  111.             }
  112.  
  113.  
  114.             byte[] TamanoFicheroBytes = Encoding.ASCII.GetBytes(NombreFichero);
  115.             if (TamanoFicheroBytes.Length > 99999 * 2024)
  116.             {
  117.                 addText("Tamaño del archivo es más de 200MB, por favor, pruebe con archivos pequeños.");
  118.                 return;
  119.             }
  120.  
  121.             //Msg = "Creando Cache buffer ...";
  122.             byte[] DatosFichero = File.ReadAllBytes(RutaFichero + NombreFichero);
  123.            
  124.             byte[] TamanoFicheroEnviar = new byte[4 + TamanoFicheroBytes.Length + DatosFichero.Length];
  125.             addText("El peso a enviar " + TamanoFicheroBytes.Length.ToString() + " bytes");
  126.  
  127.             addText("Enviando aviso de archivo y su peso");
  128.             byte[] byteAvisoArchivo = Encoding.ASCII.GetBytes("file:" + TamanoFicheroEnviar.Length.ToString());
  129.             socket.Send(byteAvisoArchivo);
  130.  
  131.             byte[] fileNameLen = BitConverter.GetBytes(TamanoFicheroBytes.Length);
  132.  
  133.             fileNameLen.CopyTo(TamanoFicheroEnviar, 0);
  134.             TamanoFicheroBytes.CopyTo(TamanoFicheroEnviar, 4);
  135.             DatosFichero.CopyTo(TamanoFicheroEnviar, 4 + TamanoFicheroBytes.Length);
  136.  
  137.             addText("Enviando archivo...");
  138.             int bytesEnviados = socket.Send(TamanoFicheroEnviar);
  139.             addText("Se enviaron " + bytesEnviados.ToString() + " bytes");
  140.  
  141.             addText("Enviando aviso que se termino de enviar el archivo");
  142.             byte[] byteAvisoEndArchivo = Encoding.ASCII.GetBytes("endfile");
  143.             //socket.Send(byteAvisoEndArchivo);
  144.         }
  145.  
  146.         private void addText(string texto)
  147.         {
  148.             if (textBox2.InvokeRequired)
  149.             {
  150.                 SetTextCallback d = new SetTextCallback(addText);
  151.                 this.Invoke(d, new object[] { texto });
  152.             }
  153.             else
  154.             {
  155.                 string datetime = DateTime.Now.ToString();
  156.                 string[] partes = datetime.Split(' ');
  157.                 string hora = partes[1] + " " + partes[2];
  158.  
  159.                 if (textBox2.Text == "")
  160.                 {
  161.                     textBox2.Text = hora + " " + texto;
  162.                 }
  163.                 else
  164.                 {
  165.                     textBox2.Text = hora + " " + texto + "\r\n" + textBox2.Text;
  166.                 }
  167.             }
  168.         }
  169.  
  170.         private void button3_Click(object sender, EventArgs e)
  171.         {
  172.             if (socket.Connected)
  173.             {
  174.                 enviarTexto(textBox3.Text);
  175.  
  176.                 if (textBox3.Text == "close")
  177.                 {
  178.                     desconectar();
  179.                 }
  180.  
  181.                 textBox3.Text = "";
  182.             }
  183.         }
  184.  
  185.         private void enviarTexto(string texto) {
  186.             if (this.InvokeRequired)
  187.             {
  188.                 SetTextCallback d = new SetTextCallback(enviarTexto);
  189.                 this.Invoke(d, new object[] { texto });
  190.             }
  191.             else
  192.             {
  193.                 byte[] msn = System.Text.Encoding.ASCII.GetBytes(texto);
  194.                 socket.Send(msn);
  195.             }
  196.         }
  197.  
  198.         private void checarMensajes(object orSocket)
  199.         {
  200.             //bool conectado = true;
  201.             int numPasadas = 1;
  202.             Socket socket = (Socket) orSocket;
  203.             addText("Iniciando escucha");
  204.             while (true)
  205.             {
  206.                 if (socket.Connected)
  207.                 {
  208.                     byte[] bytesRecibidos = new byte[1024];
  209.                     int info = socket.Receive(bytesRecibidos);
  210.                     string texto = System.Text.Encoding.ASCII.GetString(bytesRecibidos, 0, info);
  211.  
  212.                     if (texto == "recibido")
  213.                     {
  214.                         addText("Se recibio mensaje del servidor");
  215.                         enviarTexto("endfile");
  216.                     }
  217.                     numPasadas++;
  218.                 }
  219.                 checarMensajesNum(numPasadas.ToString());
  220.             }
  221.  
  222.         }
  223.  
  224.         private void checarMensajesNum(string num)
  225.         {
  226.             if (this.InvokeRequired)
  227.             {
  228.                 SetTextCallback d = new SetTextCallback(checarMensajesNum);
  229.                 this.Invoke(d, new object[] { num });
  230.             }
  231.             else
  232.             {
  233.                 textBox4.Text = num;
  234.             }
  235.         }
  236.     }
  237. }

El código del servidor lo coloco en otro post porque rebazo el limite de caracteres...
__________________
Listo?, tendría que tener 60 puntos menos de IQ para considerarme listo!!!
-- Sheldon Cooper
http://twitter.com/nemutagk
PD: No contestaré temas vía mensaje personal =)