Ver Mensaje Individual
  #2 (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: 20 años, 1 mes
Puntos: 406
Respuesta: Problema con socket y envió de imágenes C#

Código del servidor (el que recibe)

Sevidor (el que recibe)
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 RecibirArchivos
  15. {
  16.     public partial class Form1 : Form
  17.     {
  18.         Thread trabajo;
  19.         bool nextDataFile = false;
  20.         string nombreFile;
  21.  
  22.         public Form1()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.  
  27.         delegate void SetTextCallback(string text);
  28.         delegate void SetBytesCallback(int fichero, int ficheroNameLen, string nombre);
  29.  
  30.         private void button1_Click(object sender, EventArgs e)
  31.         {
  32.             ParameterizedThreadStart conexion = new ParameterizedThreadStart(escuchar);
  33.             trabajo = new Thread(conexion);
  34.             trabajo.IsBackground = true;
  35.             trabajo.Start(textBox1.Text);
  36.         }
  37.  
  38.         private void escuchar(object ip)
  39.         {
  40.             IPAddress ipServer = Dns.GetHostEntry((string)ip).AddressList[0];
  41.             IPEndPoint ipEndPoint = new IPEndPoint(ipServer, 1050);
  42.  
  43.             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  44.             socket.Bind(ipEndPoint);
  45.             socket.Listen(100);
  46.  
  47.             addText("Escuchando puerto...");
  48.             Socket conexion = socket.Accept();
  49.             addText("Conectado!!!");
  50.  
  51.             bool conectado = true;
  52.             bool isFile = false;
  53.  
  54.             BinaryWriter ArchivoBinario = null;
  55.             int fileNameLen = 0;
  56.             bool createFile = false;
  57.             string totalSizeFile = "";
  58.             string NombreFichero = "";
  59.             int recibeSizeFile = 0;
  60.  
  61.             while (conectado)
  62.             {
  63.                 if (!isFile)
  64.                 {
  65.                     byte[] bytesRecibe = new byte[1024];
  66.                     int datosRecibe = conexion.Receive(bytesRecibe);
  67.                     addText("Se recibieron " + datosRecibe.ToString() + " bytes");
  68.                     string mensaje = System.Text.Encoding.ASCII.GetString(bytesRecibe, 0, datosRecibe);
  69.                     string[] partes = mensaje.Split(':');
  70.                     if ((string)partes[0] == "file")
  71.                     {
  72.                         addText("Se va a recibir un archivo de " + partes[1] + " bytes");
  73.                         totalSizeFile = partes[1];
  74.                         isFile = true;
  75.                     }
  76.                     else if (mensaje == "close")
  77.                     {
  78.                         conectado = false;
  79.                     }
  80.                     else
  81.                     {
  82.                         addText(mensaje);
  83.                     }
  84.                 }
  85.                 else
  86.                 {
  87.                     byte[] TamanioDatos = new byte[2024 * 99999];
  88.                     addText("Recibiendo archivo...");
  89.                     int BytesRecibidosLen = conexion.Receive(TamanioDatos);
  90.                     recibeSizeFile = recibeSizeFile + BytesRecibidosLen;
  91.                    
  92.                     addText("Se recibieron " + BytesRecibidosLen.ToString() + " bytes");
  93.  
  94.                     if (!createFile)
  95.                     {
  96.                         fileNameLen = BitConverter.ToInt32(TamanioDatos, 0);
  97.                         addText("fileNameLen: " + fileNameLen.ToString());
  98.                     }
  99.                     else
  100.                     {
  101.                         fileNameLen = 0;
  102.                     }
  103.  
  104.                     if (NombreFichero == "")
  105.                     {
  106.                         NombreFichero = Encoding.ASCII.GetString(TamanioDatos, 4, fileNameLen);
  107.                         addText("Obtenemos el nombre del archivo: " + NombreFichero);
  108.                     }
  109.  
  110.                     string rutaArchivo = "D:/prueba/" + NombreFichero;
  111.  
  112.                     if (!createFile)
  113.                     {
  114.                         addText("Creando archivo en disco: " + rutaArchivo);
  115.                         ArchivoBinario = new BinaryWriter(File.Open(rutaArchivo, FileMode.Append));
  116.                         createFile = true;
  117.                     }
  118.  
  119.                     addText("Guardando archivo");
  120.                     ArchivoBinario.Write(TamanioDatos, 4 + fileNameLen, BytesRecibidosLen - 4 - fileNameLen);
  121.  
  122.                     if (recibeSizeFile.ToString() == totalSizeFile)
  123.                     {
  124.                         ArchivoBinario.Close();
  125.                         addText("Archivo recibido y guardado");
  126.                         addText("En total se recibio " + recibeSizeFile.ToString() + " bytes");
  127.                         isFile = false;
  128.                         createFile = false;
  129.                         recibeSizeFile = 0;
  130.                         NombreFichero = "";
  131.                     }
  132.                 }
  133.             }
  134.  
  135.             addText("Cerrando la conexion");
  136.             conexion.Shutdown(SocketShutdown.Both);
  137.             socket.Close();
  138.             addText("Conexion cerrada");
  139.         }
  140.        
  141.         private void addText(string texto)
  142.         {
  143.             if (textBox2.InvokeRequired)
  144.             {
  145.                 SetTextCallback d = new SetTextCallback(addText);
  146.                 this.Invoke(d, new object[] { texto });
  147.             }
  148.             else
  149.             {
  150.                 string datetime = DateTime.Now.ToString();
  151.                 string[] partes = datetime.Split(' ');
  152.                 string hora = partes[1] + " " + partes[2];
  153.  
  154.                 if (textBox2.Text == "")
  155.                 {
  156.                     textBox2.Text = hora + " " + texto;
  157.                 }
  158.                 else
  159.                 {
  160.                     textBox2.Text = hora + " " + texto + "\r\n" + textBox2.Text;
  161.                 }
  162.             }
  163.         }
  164.     }
  165. }

Se me olvidaba una cosa que también me sucede, en un equipo con Windows XP y NET Framework 4 no funciona, abre pero cuando pongo a escucha el servidor se cierra, es necesario instalar las otras versiones de NET Framework?
__________________
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 =)

Última edición por Nemutagk; 31/12/2010 a las 06:40